0

So I am trying to read from a text file. It shows that I can successfully read from the file But when I try to cout the values, it just shows 0, while I have other values in the text file.

#include <iostream>
#include <fstream>
#include <string>


using namespace std;

int main()
{

    std::ifstream file("numbers.txt");
if (file) {
    cout << "Managed to read file successfully. \n";
}else{
    cout << "Unable to read file.";
}


int x, y;

file >> x >> y;

cout << "Num 1: " << x << endl;
cout << "Num 2: " << y << endl;

    return 0;
}
huysentruitw
  • 27,376
  • 9
  • 90
  • 133
  • 1
    Please show the contents of the file. – Barmar Dec 30 '15 at 07:06
  • When you print `Managed to read file successfully`, you haven't read anything from the file. All you've done is open it. – Barmar Dec 30 '15 at 07:07
  • Why does this question sound so eerily like http://stackoverflow.com/questions/34489267/how-to-read-data-from-files-in-turbo-c-4-0 and http://stackoverflow.com/questions/34486953/how-to-read-numbers-on-text-files-using-turbo-c-4-0 ? Is there an online class going on right now or something? – Rob Starling Dec 30 '15 at 07:55

2 Answers2

0

The above code will print status of your operation,if you want to read and display contents the you have to write your code like this:

#include<iostream>
#include<fstream>

using namespace std;         

int main()    
{
            ifstream stream1("D:\\file1.txt");    
            char a[80];

            if(!stream1)    
            {
                        cout << "While opening a file an error is encountered" << endl;    
            }    
            else    
            {    
                        cout << "File is successfully opened" << endl;    
            }

            while(!stream1.eof())    
            {    
                        stream1 >> a;    
                        cout << a << endl;    
            }

            return(0);    
}
noname
  • 43
  • 5
Ananthakumar
  • 323
  • 1
  • 14
  • 1
    [Why is iostream::eof inside a loop condition considered wrong?](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – Barmar Dec 30 '15 at 07:20
0

With the numbers.txt file

45
15

Your code work find with gcc.

int main()
{
     std::ifstream file("numbers.txt");
     if (file) 
     {
        cout << "Managed to read file successfully. \n";
        int x, y;
        file >> x >> y;

        cout << "Num 1: " << x << endl;
        cout << "Num 2: " << y << endl;
    }
    else
    {
        cout << "Unable to read file.";
    }
    return 0;
}
noname
  • 43
  • 5
  • This isn't an answer, it doesn't explain what's wrong with his program or how you fixed it. It should be a comment. When you get reputation = 50 you'll be able to comment on other people's questions. – Barmar Dec 30 '15 at 07:23