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.
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.
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 .
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.
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;
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With