nkgktgkrgktrgrgtjgiortjgiorjitrgoit
-
What does `numbers.txt` look like? – Paul Rooney Jul 19 '16 at 01:48
-
10 lines of single digit numbers – Andrew Jul 19 '16 at 01:49
-
You should check if the file is opened correctly – DimChtz Jul 19 '16 at 01:52
-
figured it out. thanks all. XCode must have its settings changed to allow files to be accessed from a custom directory. – Andrew Jul 19 '16 at 01:56
2 Answers
You could be doing many things wrong.
1) The file numbers.txt does not exist, and this code fails to check that the file was successfully opened.
2) The file numbers.txt exists, but does not contain ten integer numbers, separated by whitespace, and this code fails to check whether operator>> succeeded, or not.
3) This code also prints ten numbers to std::cout without any separating character. At best, the output you will get is what looks line one large number.
So, there are at least two or three things that are wrong here. You need to fix all of them:
A) Verify that the file has been opened succesfully.
B) After every operator>> invocation, check if the file stream is good(), or not.
- 98,597
- 5
- 74
- 125
If you are not sure whether the file exists, or whether it is in the same directory as your executable, modify your code to check if the file opened, like this for example:
void readFile() {
ifstream read("numbersd.txt");
if(!read) { cerr << "File didn't open..Does it exist?" << endl; return; }
...
Then, if it didn't open, here are some things that might be happening:
- File doesn't exist.
- File is not in the path you think it is.
- You don't have the rights to access that file.
The problem lies in the file, since the code works fine, given that the file numbers.txt exists (and it's in the same directory with your executable file) I used that one for example:
1
2
3
4
5
6
7
8
9
10
and the result is:
C02QT2UBFVH6-lm:~ gsamaras$ g++ main.cpp
C02QT2UBFVH6-lm:~ gsamaras$ ./a.out
1 2 3 4 5 6 7 8 9 10
And this is the code I used from you:
#include <iostream>
#include <fstream>
using namespace std;
class myClass {
public:
void readFile() {
ifstream read("numbers.txt");
for(int i=0;i<10;i++)
read>>sPerDay[i];
for (int i = 0;i<10;i++) {
cout << sPerDay[i] << " ";
}
cout << "\n";
}
private:
int sPerDay[10];
};
int main() {
myClass obj;
obj.readFile();
return 0;
}