How to read formatted data in C++?

TheOnly92 picture TheOnly92 · Aug 24, 2010 · Viewed 26.5k times · Source

I have formatted data like the following:

Words          5
AnotherWord    4
SomeWord       6

It's in a text file and I'm using ifstream to read it, but how do I separate the number and the word? The word will only consist of alphabets and there will be certain spaces or tabs between the word and the number, not sure of how many.

Answer

Donotalo picture Donotalo · Aug 24, 2010

Assuming there will not be any whitespace within the "word" (then it will not be actually 1 word), here is a sample of how to read upto end of the file:

std::ifstream file("file.txt");
std::string str;
int i;

while(file >> str >> i)
    std::cout << str << ' ' << i << std::endl;