The last word on the line is unreadable

I am currently working on a program that reads each line from a file and extracts a word from the line using a special delimiter.

So basically my code looks like this

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main(int argv, char **argc)
{
  ifstream fin(argc[1]);
  char delimiter[] = "|,.\n ";
  string sentence;

  while (getline(fin,sentence)) {
     int pos;
     pos = sentence.find_first_of(delimiter);
     while (pos != string::npos) {
        if (pos > 0) {
           cout << sentence.substr(0,pos) << endl;
        }
          sentence =sentence.substr(pos+1);
          pos = sentence.find_first_of(delimiter);
      }
  }
}

      

However, my code didn't read the last word in the line. For example, my file looks like this. Hello World

exiting the program is just the word "hello", not "world". I am using '\ n' as separator, but why doesn't that work?

Any hint would be appreciated.

0


a source to share


3 answers


getline does not store the new string character in the string. For example, if your file has the line "Hello World \ n" getline will read that line "Hello World \ 0" So your code is skipping over "World".

Ignoring this sentence is undefined, you can change your code this way:



#include<iostream>
#include<fstream>
using namespace std;

int main(int argv, char *argc)
{
  ifstream fin(argc[1]);
  char delimiter[]="|,.\n ";
  while (getline(fin,sentence)) {
     sentence += "\n";
     int pos;   
     pos = find_first_of(sentence,delimiter);
     while (pos != string:: npos) {
        if (pos > 0) {
           cout << sentence.substr(0,pos) << "\n";
        }
          sentence =sentence.substr(pos+1);
          pos = find_first_of(sentence,delimiter);
      }
  }
}

      

Note. I borrowed Bill of the Lizards a more elegant solution to add the last delimiter. My previous version had a loop exit condition.

+2


a source


To paraphrase this reference document :

The characters are retrieved until the discarded character ( \n

) is found and the remaining characters are returned.



Your line doesn't end with \n

, it is ^`hello world`$

, so there is no delimiter or new pos.

+2


a source


As mentioned, getline does not return a newline character at the end. The easiest way to fix your code is to add one to the end of the sentence after the getline call.

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main(int argv, char **argc)
{
  ifstream fin(argc[1]);
  char delimiter[] = "|,.\n ";
  string sentence;

  while (getline(fin,sentence)) {
     sentence += "\n";
     int pos;
     pos = sentence.find_first_of(delimiter);
     while (pos != string::npos) {
        if (pos > 0) {
           cout << sentence.substr(0,pos) << endl;
        }
          sentence =sentence.substr(pos+1);
          pos = sentence.find_first_of(delimiter);
      }
  }
}

      

+1


a source







All Articles