Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read formatted data in C++?

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.

like image 450
TheOnly92 Avatar asked Aug 24 '10 11:08

TheOnly92


People also ask

What is formatted data in C?

The format specifiers are used in C for input and output purposes. Using this concept the compiler can understand that what type of data is in a variable during taking input using the scanf() function and printing using printf() function. Here is a list of format specifiers.

What does fscanf() do?

The fscanf() function reads data from the current position of the specified stream into the locations that are given by the entries in argument-list , if any. Each entry in argument-list must be a pointer to a variable with a type that corresponds to a type specifier in format-string .

What fscanf return in C?

Return Value This function returns the number of input items successfully matched and assigned, which can be fewer than provided for, or even zero in the event of an early matching failure.


2 Answers

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;
like image 87
Donotalo Avatar answered Sep 18 '22 09:09

Donotalo


The >> operator is overridden for std::string and uses whitespace as a separator

so

ifstream f("file.txt");

string str;
int i;
while ( !f.eof() )
{
  f >> str;
  f >> i;
  // do work
}
like image 34
mmmmmm Avatar answered Sep 17 '22 09:09

mmmmmm