0

I am trying to read and store data from a file from my computer using ifstream, but after building and compiling, my command line interface does not display the output that I am expecting. My code looks like:

#include <iostream>
using namespace std;
int main ()
{
    int num1;

    ifstream file_In;
    file_In.open("YES");
    file_In >> num1;
    cout << num1 << endl;

    file_In.close();
    return 0;
}

I have a text file named "YES" on my desktop and it simply contains the text: 10 20 5 5 5 7

and I am expecting to see the number 10 displayed on my command line interface but instead, I get a 0.

E. Lee
  • 3
  • 3
  • 2
    You always need to check for the results of functions that you call. To know which results to expect, read the relevant documentation. – Kerrek SB Jan 14 '18 at 02:29
  • to elaborate, you don't know if your `.open()` call actually opened a file. you can check though: https://stackoverflow.com/questions/4206816/ifstream-check-if-opened-successfully – kmdreko Jan 14 '18 at 02:36
  • 2
    give it the full path or put the file in the same dir as the program – bolov Jan 14 '18 at 02:41
  • the file and the program are both saved onto my desktop @bolov – E. Lee Jan 14 '18 at 02:52
  • Doesn't the file have an extension (e.g. `.txt`)? – O'Neil Jan 14 '18 at 02:56
  • 1
    On Windows, the setting "Hide file extensions for known file types" is a programmer's worst enemy. [Turn it off.](https://www.howtogeek.com/205086/beginner-how-to-make-windows-show-file-extensions/) – Ben Voigt Jan 14 '18 at 03:01

1 Answers1

-2

Most likely you are running into a problem of incorrect file path. I made a small change in your program and it works fine. So try giving the full path starting from drive name e.g. "C:\nitin\progs\YES".

main()
{
    int num1;

    ifstream file_In;
    file_In.open("C:\\nitin\\progs\\YES");
    file_In >> num1;
    cout << num1 << endl;
    file_In.close();
}
Nitin
  • 145
  • 9
  • 2
    Why are you not checking that the file is opened? Why are you not checking that you are able to read an integer? – Ed Heal Jan 14 '18 at 03:30
  • 1
    ifstream::open returns void. In order to check for file open error he will need to check if any exception was thrown or not. as he is very new to programming I gave him a simpler solution. – Nitin Jan 14 '18 at 03:42
  • 1
    Please - write code in the first place to check if it open and therefore fault tolerant . i.e. use `file_In.is_open()` – Ed Heal Jan 14 '18 at 03:47
  • 1
    @Nitin I am not very new to programming. :-) std::ifstream does not throw exceptions. It sets fail-bits. It is necessary to check to see if ifstream::operator >> (int) failed also. – Jive Dadson Jan 14 '18 at 07:15
  • @Nitin Thank you! Putting in the full file path solved my problem! – E. Lee Jan 14 '18 at 23:58