How do you know when the input stream has reached the last word in a line?

I am reading input from ifstream in C ++. The input comes as a bunch of words, separated by tabs, so I read something like the word word2 word3 as stream → w1 → w2 → w3; I need to know when I get to the last word in a string, so how can I do this? The number of words is variable, but it must always be even. Also, will the last word contain \ n or will \ n be the last?

+1
source share
3 answers

The simplest (and usual) solution is to read the lines using std::getline , and then std::istringstream line using std::istringstream :

 std::string line; while ( std::getline( std::cin, line ) ) { std::istringstream s( line ); std::vector<std::string> words; std::string word; while ( s >> word ) { words.push_back( word ); } // ... } 
+8
source

Read from ifstream and push it into a vector using algorithm std::copy , as shown below:

 std::ifstream stream("input.txt"); std::vector<std::string> vec; //replace stream with std::cin for reading from console std::copy(std::istream_iterator<std::string>(stream), std::istream_iterator<std::string>(), std::back_inserter(vec)); 

EOF is required to complete. Ctrl + Z or Ctrl + D depends on windows or Linux.

As suggested, you can use the C ++ 11 initializer list as follows:

 std::vector<std::string> vec{std::istream_iterator<std::string>{stream}, std::istream_iterator<std::string>{}}; 
+3
source

I would advise the mmap() file. After that, you have the whole file in your virtual address space and you can check it at your leisure, like a large array of characters. Especially for such operations, when you need to go back a few steps, this is the most suitable approach. As an added bonus, it is also the fastest ...

+1
source

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


All Articles