higgs241
higgs241

Reputation: 629

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

I'm reading input from an ifstream in C++. The input comes as a bunch of words separated by tabs, so I'm reading in something like "word1 word2 word3" as stream >> w1 >> w2 >> w3; I need to know when I've reached the final word in the line, so how would I go about that? The number of words is variable, but it should be always even. Also, will the last word contain the \n, or will the \n be the last word?

Upvotes: 1

Views: 1343

Answers (3)

P0W
P0W

Reputation: 47854

Read from ifstream and push it to vector using algorithm's std::copy like following:

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));

This needs a EOF for termination. Ctrl+Z or Ctrl+D depeding on windows or linux.

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

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

Upvotes: 3

I would advise to mmap() the file. After that, you have the entire file in your virtual address space and can examine it at leisure like a big array of characters. Especially for such operations, where you have to go back a few steps, this is the most appropriate approach. As an added bonus, it's also the fastest...

Upvotes: 1

James Kanze
James Kanze

Reputation: 154047

The simplest (and usual) solution is to read lines using std::getline, and then parse the 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 );
    }
    //  ...
}

Upvotes: 8

Related Questions