Reading values ​​from fields in a CSV file?

Yesterday I made a small script with some help to read .csv files. Although I found a way to read the first value and save it, but for some reason it saves the last value instead.

I store what I thought should be the first value under value1, and re-display it to make sure it is displayed correctly and is actually stored under the called variable.

Does anyone know what is wrong with this code? I think I should use vectors, but when I read the help sheets that I find on the Internet, I will throw a little about them. Any help is appreciated.

#include <iostream> #include <fstream> #include <string> using namespace std; int main () { int loop = 1; string value; string value1; while(loop = 1) { cout << "Welcome! \n" << endl; ifstream myfile; myfile.open ("C:/Documents and Settings/RHatfield/My Documents/C++/Product Catalog Creator/Source/External/Sample.csv"); while (myfile.good()) getline ( myfile, value, ',' ); cout << string ( value) << endl; value1 = value; cout << value1; myfile.close(); system("PAUSE"); return 0; } } 
+3
source share
2 answers

Your mistake seems to be in formatting clean code.

 while (myfile.good()) 

After the loop there is no {} . Therefore, only the next line is repeated.

The following code is executed after reading the entire file.

 cout << string ( value) << endl; 

Thus, value stores the last line of the file.

+1
source

You can change the condition in a while :

 char separator; int value1; int value2; int value3; while (myfile >> value1) { // Skip the separator, eg comma (',') myfile >> separator; // Read in next value. myfile >> value2; // Skip the separator, eg comma (',') myfile >> separator; // Read in next value. myfile >> value3; // Ignore the newline, as it is still in the buffer. myfile.ignore(10000, '\n'); // Process or store values. } 

The above code snippet is not reliable, but demonstrates the concept of reading from a file, skips non-numeric delimiters and processes the end of the line. The code is also optimized.

0
source

Source: https://habr.com/ru/post/1485872/


All Articles