tags:

views:

67

answers:

4

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 ?

+2  A: 

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;
casablanca
+3  A: 

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
}
Martin York
I was just about finished with the very same answer! `:)`
sbi
A: 

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){}
the_great_monkey
A: 

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.**
      }

      inSR.close();
      return 0;
  }
  else  // 7)
  {
    cout <<"The file " <<_filename <<" can not be opened.";
    return -1;
  }
}
Rui
Avoid identifiers that begin with underscore. http://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier/228797#228797
Martin York