Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ introduction: self study

Tags:

c++

I created the program to read from text file and remove special characters. I can't seem to code better the if statement. Please help. I searched online for the right code statements but they have all advanced code statements. The book I am learning from has the last(14th) chapter with strings and file open and closing code. I tried creating an array of special chars, 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();
like image 322
Luckwhy Avatar asked Mar 16 '26 10:03

Luckwhy


1 Answers

You might want to look into the strchr function which searches a string for a given character:

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

The strchr function locates the first occurrence of c (converted to a char) in the string pointed to by s. The terminating null character is considered to be part of the string.

The strchr function returns a pointer to the located character, or a null pointer if the character does not occur in the string.

Something like:

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

You'll have to declare curChar as a char rather than a string and use:

curChar = paragraph[subscript];

rather than:

curChar = paragraph.substr(subscript, 1);

but they're relatively minor changes and, since your stated goal was I want to change the if statement into [something] more meaningful and simple, I think you'll find that's a very good way to achieve it.

like image 178
paxdiablo Avatar answered Mar 18 '26 23:03

paxdiablo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!