I am making a very simple function, where I made an array of integers, I made the write in a file, and then I am reading from the same file and returning the number of values put on the file. Technically the value should be the same as the length of the array, however, the result is different. I have put some couts during the loop, but not understanding where the problem might be.
int len = 5;
int main()
{
int A[len];
for (int i = 0; i < len; i = i + 1) {
cout << "insert a value: " << endl;
cin >> A[i];
}
ofstream file;
file.open("trial.txt");
for (int i = 0; i < len; i = i + 1) {
file << A[i] << '\t';
}
file.close();
ifstream file1;
file1.open("trial.txt");
int val;
int conta = 0;
cout << "count before while" << conta << endl;
while (!file1.eof()) {
file1 >> val;
cout << "i am val: " << val << endl;
cout << "i am conta:" << conta << endl;
conta = conta + 1;
}
cout << "i am conta after while: " << conta << endl;
cout << "the value should be 5: " << conta; //instead it shows 6
file1.close();
}
This is standard problem!
Do not use this kind of loop: while (!file1.eof())
It doesn't work since your file ends with tab which is not read with last number and as a result loops iterates again more then it is needed. During last iteration tab is read, but reading of val
fails and you see that as duplicated value.
Fix it like this:
while (file1 >> val) {
cout << "i am val: " << val << endl;
cout << "i am conta:" << conta << endl;
conta = conta + 1;
}
It tries to read integer value and loop is exacted only when it is successful. There can be multiple reasons of stooping this loop: end of file reached, integer value not found, IO operation failure.
Offtopic: this int A[len];
is not allowed in standard C++
. It works in most compilers since it is allowed in C
. In C++ it is recommended to use std::array
(since C++11
) or std::vector
in such cases.