Take the 2-minute tour ×

I want to read each line of txt file which resembles something like this

1190/2132 123/23123 45

I want to read the whole line and then store them in three separate strings for future use to build a tree . I am using fgets right now , but getting errors regarding putting it into a string . How should i do it ?

share|improve this question
add comment

4 Answers

Try this:

std::string  line;

while(std::getline(file, line))
    std::stringstream  linestream(line);

    std::string word1, word2, word3;
    line >> word1 >> word2 >> word3;

    // Store words
share|improve this answer
I was just about finished with the very same answer! :) –  sbi Sep 21 '10 at 22:21
add comment

You've tagged the question C++, but you say you're using fgets, so I'm not sure which one you want.

Using C stdio functions:

fscanf(file, "%s %s %s", str1, str2, str3);

Using C++ streams:

input_stream >> str1 >> str2 >> str3;
share|improve this answer
add comment

This may work:

string a, b, c;

getline(cin, a, '/')
getline(cin, b, ' ')

//will only get executed if the third string exist
if(cin >> c){}
share|improve this answer
add comment

Stuff you need to get it work:

  • #include so that you can open the text file with a input file stream.
  • #include if you want to display some information on the screen as well but just optional.
  • The code part:

Pseudo code:

  • define a character array with length K, where K can be defined as a MACRO
  • open an input file stream
  • test if it is opened, if opened read a line and parse the line until the EOF.
  • if not opened, return -1.

The Code

int fileread(const char* filename, dataType& data /* some object saving the read info. */)
  char lntxt[MAX_LNTXT_LENGTH_CPTIMGIDX];  // 4)
  ifstream inSR(_filename);  // 5)

  if (inSR.is_open())  // 6)

    // If file is open

    while (inSR.peek()>0)
      inSR.getline(lntxt, MAX_LNTXT_LENGTH_CPTIMGIDX);
      // delim can be a set of possible delim
      char* strTk = strtok(lntxt, _delim);
      while (strTk != NULL)
         strTk = strtok(NULL, _delim);
         if (strTk != NULL)
         // Your code to process the data, i.e. some arithmetic operation
         // or store it in other variables or objects.**

      return 0;
  else  // 7)
    cout <<"The file " <<_filename <<" can not be opened.";
    return -1;
share|improve this answer
Avoid identifiers that begin with underscore. stackoverflow.com/questions/228783/… –  Loki Astari Sep 22 '10 at 0:28
add comment

Your Answer


