简体   繁体   中英

C++ how to ignore specific characters when reading from a text file?

i have a main function that reads a text file as such

int count = 0;
std::string fileName; 
std::fstream readFile;
std::string storeFile;
char myWord[50000];

int main(int argc, char *argv[]) {

 std::cout << "Please enter the name of the file: " << std::endl; //prompts user for the filename
 std::cin >> argv[0];  //stores the filename is the first element of argv[]

fileName = argv[0];
readFile.open(fileName);

 if(!readFile) {
      std::cerr << "ERROR: failed to open file " << std::endl;  //if the file cannot be opened an error is displayed
      exit(0); //if it cannot open the console terminates
      } else {
          std::cerr << "File successfully opened" << std::endl;
      }

      while(readFile >> storeFile){
          if(readFile.bad()) {
              std::cerr << "File failed to read " << std::endl;
              break; //loop terminates
                } else {
                   for (int i = 0; i < sizeof(myWord)/sizeof(myWord[0]); i++){
                                  readFile >> myWord[i]; 
                                  count++;
                } 
    }

    readFile.close();

An example of a snippet from the text file

'Twas brillig, and the slithy toves
Did gyre and gimble in the wabe:
All mimsy were the borogoves,
And the mome raths outgrabe.

How would i go about ignoring the puncuation when reading the file?(so igoring the symbols ', : and.)

You could read lines, replace punctation characters with spaces and then use istringstream and std::skipws to read words

You can push to temporary char, then check it char c; readFile >> c; if (....) myWord[i] = c; char c; readFile >> c; if (....) myWord[i] = c;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM