开发者

Reading Values from fields in a .csv file?

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

I store what I thought should be the first value under value1, and re-display it to make sure it displays properly and is in fact being stored under a callable variable.

Does anyone know what is wrong with this code? I think I should be using vectors but as I read the reference sheets I find on the internet about them I am being a little thrown of. 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;
    }


}


Your error seems to be in pure code formatting.

while (myfile.good())

There is no {} after the loop. So only next line is repeated.

The following code is executed after reading of the whole file.

cout << string ( value) << endl;

Thus value stores the last line of the file.


You may want to change the condition in your while loop:

char separator;
int value1;
int value2;
int value3;
while (myfile >> value1)
{
    // Skip the separator, e.g. comma (',')
    myfile >> separator;

    // Read in next value.
    myfile >> value2;

    // Skip the separator, e.g. 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 fragment is not robust but demonstrates the concept of reading from a file, skipping non-numeric separators and processing the end of the line. The code is optimized either.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜