CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Jun 2001
    Posts
    107

    Help reading input file

    I am trying to read an input file by inputing them directly into containers. This works up until the point where there is a new line and I have to go to the next. Here is the input file:

    Code:
    P1 15 32 95 51
    P2  99  5
    P1 16 92 34 77 99
    P2 Finish
    Ahead of time I dont know how many numbers will be following the P?. So far I loop through and grab each of the numbers with a line like this:

    Code:
    file >> inputNum;
    When it runs out of numbers, inputNum becomes 0. Now I need to get to the next line and start with inputing a string "P2" and then start inputing integers again. How do I get to the next line? If I keep trying to input stuff it keeps giving me 0.

    Here is my code reduced to show the important parts:

    Code:
     while( !file.eof() )
        {
            file >> process;
    
            process[0] = '0';
            
            temp->process = atoi( process );
    
          while( inputNum != 0 )
          {
              file >> inputNum;
    
              if( inputNum < 1 )
              {
                  break;
              }
                
         }
    
    }

  2. #2
    Join Date
    Aug 2000
    Location
    West Virginia
    Posts
    7,725
    I'm not eaxctly sure what you are doing, but one way
    might be to read line by line into a string, put
    the string into a stringstream, and process it.

    Here is an example :
    Code:
    #include <iostream>
    #include <fstream>
    #include <string>
    #include <sstream>
    
    using namespace std;
    
    int main()
    {
        ifstream file("lines.txt");
        if (!file)
        {
            cout << "problem with file open" << endl;
            return 0;
        }
    
        string line;
        while (std::getline(file,line))
        {
            istringstream iss(line);
            string tag;
    
            iss >> tag;
    
            cout << tag << endl;
    
            int value;
            while (iss >> value)
            {
                cout << "      " << value << endl;
            }
        }
    
        return 0;
    }
    Last edited by Philip Nicoletti; April 17th, 2003 at 01:09 PM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured