0

Is there some way to read consecutive words separated by spaces as strings until end of line is found in C++? To be precise, I'm working on an algorithmic problem and the input goes like:

some_word1 some_word2 some_word3 (...) some_wordn
other_data

And the trick is I don't know how many words will there be in the first line, just that I should read them as separate words for further processing. I know I could use getline(), but after that I'd have to work char-by-char to write each word in a new string when space occurs. Not that it's a lot of work, I'm just curious if there's a better way of doing this.

Straightfw
  • 2,143
  • 5
  • 26
  • 39

3 Answers3

4

Why would you have to work character by character after using getline? The usual way of parsing line oriented input is to read line by line, using getline, and then use an std::istringstream to parse the line (assuming that is the most appropriate parsing tool, as it is in your case). So to read the file:

std::string line;
while ( std::getline( input, line ) ) {
    std::istringstream parse( line );
    //  ...
}
James Kanze
  • 150,581
  • 18
  • 184
  • 329
2

You could use sstream and combine it with getline(), which is something you already know.

#include <iostream>
#include <sstream>

int main()
{
    std::string fl;
    std::getline(std::cin, fl); // get first line

    std::istringstream iss(fl);
    std::string word;
    while(iss >> word) {
        std::cout << "|" << word << "|\n";
    }

    // now parse the other lines
    while (std::getline(std::cin, fl)) {
      std::cout << fl << "\n";
    }
}

Output:

a b
|a|
|b|
a
a
g
g
t
t

You can see that the spaces are not saved.


Here you can see relevant answers:

  1. Split a string in C++
  2. Taking input of a string word by word
Community
  • 1
  • 1
gsamaras
  • 71,951
  • 46
  • 188
  • 305
  • And since the question is a duplicate, why answer and not vote to close? – jpw Nov 05 '14 at 23:47
  • Oh I thought that we should answer the question, wait for a question to be accepted and then vote for duplicate @jpw. Guess I was wrong! Should I delete the answer? – gsamaras Nov 05 '14 at 23:48
  • Nah, don't bother. It won't be closed now anyway. – jpw Nov 05 '14 at 23:49
  • OK, I will have it in mind for the future. I will vote for a duplicate too. Thanks @jpw – gsamaras Nov 05 '14 at 23:50
0

I would suggest to read the complete line as a string and split the string into a vector of strings. Splitting a string can be found from this question Split a string in C++?

string linestr;
cin>>linestr;
string buf; // Have a buffer string
stringstream ss(linestr); // Insert the string into a stream

vector<string> tokens; // Create vector to hold our words

while (ss >> buf)
    tokens.push_back(buf);
Community
  • 1
  • 1
Srinath Mandava
  • 3,384
  • 2
  • 24
  • 37