CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Jan 2008
    Posts
    11

    Open File and Read

    Hey guys I'm having trouble figuring this out.

    I'm use fstream to open the file...

    Now how can I get my program to read data from the file and store them into variables?

    Code:
     
    for (;;)
      {
        fstream filestr;
    
        filestr.open (File);
    
    
        // Skip leading white space
        double G = 0, H = 0, L, Item;
    
    //PROBLEM STARTS HERE
        cin >> ws;
    
        if (cin.eof()) break;
    
        // Look ahead at next character in the input stream (without consuming it)
    
        if ( isdigit( cin.peek() ) )
        {
          // Next character was a numeric digit, so input a real number
    
          cin >> D;
          cout << "Number: " << D << endl;
    I'm using Linux right now, a.out < filename works just fine.
    But I have to use this format: a.out filename filename2 filename3.

    Do I even use cin?

    Thank you.

  2. #2
    Join Date
    Apr 2008
    Posts
    15

    Re: Open File and Read

    OK, when you are reading in from a file you do not use cin. Instead you use the fstream variable name. So using your code:

    Code:
    fstream filestr;
    
    filestr >> ws;
    I hope this helps.

  3. #3
    Join Date
    Mar 2007
    Location
    Montreal, Quebec, Canada
    Posts
    185

    Re: Open File and Read

    When using a command line like this:
    Code:
    a.out < file1
    it loads the file in using cin (only on Linux too, this won't work on Windows), but like this:
    Code:
    a.out file1 file2
    You have to use command line arguments. So in your main function:
    Code:
    int main(int argc, char * argv[]){
        for (int i = 1; i < argc; i++){
            ifstream file(argv[i]);
    
            //process each file here
         
        }
    }
    argv is an array of all the arguments to your program. argv[0] is the name of your program (in the example it would be "a.out") and the rest would be any other arguments you passed. The argc variable tells you how many arguments were passed.

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