7

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 ?

Hick
  • 35,524
  • 46
  • 151
  • 243

4 Answers4

4

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
  • 257,169
  • 86
  • 333
  • 562
2

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
  • 69,683
  • 7
  • 133
  • 150
0

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){}
Enrico Susatyo
  • 19,372
  • 18
  • 95
  • 156
0

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;
  }
}
Community
  • 1
  • 1
Curious
  • 21
  • 5
  • 1
    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 Sep 22 '10 at 00:28