Introduction to C ++: Self-Study

I created a program to read from a text file and remove special characters. I can't better code the if statement. Please help. I searched online for the correct code statements, but they have all the advanced code statements. The book I am studying has the last (14th) chapter with lines and a file of open and closing code. I tried to create an array of special characters, but did not work. Please help me!

     int main()
     {


 string paragraph = "";
 string curChar = "";
 string fileName = "";
 int subscript=0;
 int numWords=0;


 ifstream inFile; //declaring the file variables in the implement
 ofstream outFile;


       cout << "Please enter the input file name(C:\owner\Desktop\para.txt): " << endl;

       cin >> fileName;


 inFile.open(fileName, ios::in); //opening the user entered file

 //if statement for not finding the file
 if(inFile.fail())
 {
  cout<<"error opening the file.";
 }
 else
 {
 getline(inFile,paragraph);
 cout<<paragraph<<endl<<endl;
 }


 numWords=paragraph.length();

 while (subscript < numWords)
 {

  curChar = paragraph.substr(subscript, 1);


      if(curChar==","||curChar=="."||curChar==")"
   ||curChar=="("||curChar==";"||curChar==":"||curChar=="-"
   ||curChar=="\""||curChar=="&"||curChar=="?"||
      curChar=="%"||curChar=="$"||curChar=="!"||curChar=="                ["||curChar=="]"||
   curChar=="{"||curChar=="}"||curChar=="_"||curChar=="  <"||curChar==">"
     ||curChar=="/"||curChar=="#"||curChar=="*"||curChar=="_"||curChar=="+"
   ||curChar=="=")


  {
   paragraph.erase(subscript, 1);
   numWords-=1;
  }
  else 
   subscript+=1;

 }

 cout<<paragraph<<endl;
 inFile.close();
+3
source share
3 answers

You might want to examine a function strchrthat looks for a string for a given character:

include <string.h>
char *strchr (const char *s, int c);

strchr c ( char) , s. .

strchr , .

- :

if (strchr (",.();:-\"&?%$![]{}_<>/#*_+=", curChar) != NULL) ...

curChar char, string :

curChar = paragraph[subscript];

:

curChar = paragraph.substr(subscript, 1);

, , I want to change the if statement into [something] more meaningful and simple, , , .

+3

<cctype> , isalnum(c), true iff c alpanumeric, isdigit(c) .. , , ,

if(isgraph(c) && !isalnum(c))

c char, std::string (, c int, :) hth

P.S. , std::string curChar, c char c = curChar[0]

+1

since you are learning C ++, I will tell you about the C ++ iterator eraser.

for (string::iterator it = paragraph.begin();
        it != paragraph.end();
        ++it)
    while (it != paragraph.end() && (*it == ',' || *it == '.' || ....... ))
        it = paragraph.erase(it);

Try using first iterator. This will not give you maximum performance, but its concept will help you work with a different C ++ framework.

if(curChar==","||curChar=="."||curChar==")"  ......

Secondly, the single quote 'and double quote "are different. You use 'to char.

0
source

Source: https://habr.com/ru/post/1778255/


All Articles