Hello jefazo92,
It helps if you compile the program before you post it. You would have found errors that you could have corrected or asked about.
You program used an input file. Post the input file or at least a fair sample so everyone knows what to work with and exactly how it is laid out.
You are missing the closing parentheses of "main". And on line 17, What type of string is it?
As
jonnin is saying
while (!myFile.eof())
does not work the way you are thinking. Line 18 enters the loop because "eof" is not set yet. line 19 reads the last available entry and line 20 processes it. Going back to the loop condition "eof" is not set yet so you enter the loop. line 19 tries to read past "eof" and can not, so "eof" is set on the stream, but you still process line 20 with the last information in the array. Only then after you have processed the last read twice does the while condition fail.
One way to use this could be
1 2 3 4 5 6 7 8
|
myFile >> x[k];
while (!myFile.eof())
{
std::cout << x[k++] << std::endl;
myFile >> x[k];
}
| |
With the the read at the end of the loop and the first read before the loop. The while condition will fail at the correct time.
Not knowing what the input file looks like there is another potential problem that the formatted input is likely to cause.
The following code should give you an ides for improvements.
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 30 31 32
|
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
int main() // <--- Missing closing ).
{
int k = 0;
// Open Stream
std::ifstream myFile("hello.csv");
if (!myFile)
{
std::cout << "Error opening file" << std::endl;
return 0;
}
// transfer data
std::string x[2000];
while (std::getline(myFile,x[k], ','))
{
std::cout << x[k++] << std::endl;
}
//close stream
myFile.close();
return 0;
}
| |
One last thing I noticed is that "k" is defined and set to zero, but its value never changes. So, everything that you might read goes into element
x[0]
leaving 1999 unused elements. Seems a waste right now.
Also a few well placed blank lines really help to make it easier to read the code.
Hope that helps,
Andy