Assistance with this code

I am simply trying to read information from a text file. I have created a text file already with the name inData.txt. Here is what I have in my text file:

10.20 5.35
15.6
Randy Gill 31
18500 3.5
A

Here is my code:

#include <iostream>
#include <iomanip>
#include <fstream>


using namespace std;

int main()
{
ifstream inFile;

double length, width;

inFile.open("inData.txt");


cout << setprecision(2) << showpoint << fixed;

inFile >> length >> width;

cout << "length = " << length << " width = " << width << endl;

return 0;
}

Why does my output continue to be: length = 0.00 width = 0.00 ??

Last edited on
I'd make sure that you've actually opened the file. There's an is_open() function in the fstream header - http://www.cplusplus.com/reference/fstream/fstream/is_open/
Okay, so I have checked to see if the file was successfully opened. It appears not to be...So, why would my text file have troubles opening? I have used the exact name of the text file in my code.
Hopefully the underlying library sets errno on error. Try adding this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <iomanip>
#include <fstream>
#include <cerrno>
#include <cstring>


using namespace std;

int main()
{
ifstream inFile;

double length, width;

inFile.open("inData.txt");
if (!inFile) {
    cout << "Can't open inData.txt: " << strerror(errno) << endl;
}


cout << setprecision(2) << showpoint << fixed;

inFile >> length >> width;

cout << "length = " << length << " width = " << width << endl;

return 0;
}
I'm not sure if there are any errors in your code, as I am new to C++ (and programming). However, I have had this problem before. My issue was the location of my text file. I had to store the text file in the same folder as the source for my code.

I'm not sure if you have already done this, but I feel like it is the simplest thing to try before messing with all of the code. I'm sorry if this doesn't help!
Bravo my friend! Thanks a ton for that advice. I can't believe I didn't come up with that beforehand. Success!
Topic archived. No new replies allowed.