How to read formatted data in C++?

29,343

Solution 1

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;

Solution 2

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
}

Solution 3

sscanf is good for that:

#include <cstdio>
#include <cstdlib>

int main ()
{
  char sentence []="Words          5";
  char str [100];
  int i;

  sscanf (sentence,"%s %*s %d",str,&i);
  printf ("%s -> %d\n",str,i);

  return EXIT_SUCCESS;
}

Solution 4

It's actually very easy, you can find the reference here
If you are using tabs as delimiters, you can use getline instead and set the delim argument to '\t'. A longer example would be:

#include <vector>
#include <fstream>
#include <string>

struct Line {
    string text;
    int number;
};

int main(){
    std::ifstream is("myfile.txt");
    std::vector<Line> lines;
    while (is){
        Line line;
        std::getline(is, line.text, '\t');
        is >> line.number;
        if (is){
            lines.push_back(line);
        }
    }
    for (std::size_type i = 0 ; i < lines.size() ; ++i){
        std::cout << "Line " << i << " text:  \"" << lines[i].text 
                  << "\", number: " << lines[i].number << std::endl;
    }
}
Share:
29,343
TheOnly92
Author by

TheOnly92

Updated on July 09, 2022

Comments

  • TheOnly92
    TheOnly92 almost 2 years

    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.