Click here to Skip to main content
15,895,011 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hi,
I have some data in csv/txt file in below format:
7/11/2012 6:45,7/12/2012 6:45,1.0139,1.0123,1.0067,1.0236,1.0253,1.0289,
7/11/2012 6:45,7/12/2012 6:45,96.95,97.08,96.86,0,0,0,
7/11/2012 6:45,7/12/2012 6:45,1.5507,1.5487,1.5441,1.5623,1.5639,1.5691,

I am trying parsing this lines and write in another csv file. CSV must be include different rows & columns.
My code is:

C++
void readInput(char* fileName) {
    printf("****************ReadInput***************\n");

    // read file
    ifstream fin(fileName);
    string tmp = ""; // a line in the input file
    while(getline(fin, tmp)) {
        // add string into vector
        listString.push_back(tmp);
        cout << listString[listString.size() - 1] << endl;
    }
    printf("\n\n");
    fin.close();
}

/*
 * parseValues is to extract data in the input file
 */
void parseValues() {
    printf("****************ParseValue***************\n");
    for (int i = 0; i < listString.size(); ++i) {
        char tmp[100000];
		
        strcpy(tmp, listString[i].c_str()); // copy string to char array
        stringArray tmpArray;
        // utilize string token to extract data
        char * pch;
        pch = strtok (tmp,",");
        while (pch != NULL) {
            tmpArray.push_back(pch);
           printf ("%s\t",pch); 
            // get the next token
            pch = strtok (NULL, ",");
			
        }
        data.push_back(tmpArray);
		
        printf("\n");
    }
}

/*
 * parseValues is to write data at the beginning of file
 */
void writeOutput01(char* fileName) {
    ofstream fout(fileName);
    // for each row
    for (int i = 0; i < listString.size(); ++i) {
        // for each column
        for (int j = 0; j < data[i].size(); ++j)
            fout << data[i][j] << ',';
        fout << "\n";
    }
    fout.close();
}


When it parsing and write, writes in 3 rows and one column.
It writes in one column instead 8 columns for each line.
How to fix this?
Regards,
Posted
Updated 18-Feb-18 8:18am

You think that "\n" is the end of line character, but it is not exactly so. Unfortunately, it depends on your platform. Please see:
http://en.wikipedia.org/wiki/End_of_line[^].

You need to write end of line in a way specific for your platform or make it cross-platform. Please see:
http://stackoverflow.com/questions/8689344/portable-end-of-line-newline-in-c[^].

—SA
 
Share this answer
 
int n=1, k=2,l=9;

ofstream o,a;

o.open("test.csv", ios::app) ;
o<<n<<","<<l<<","<<k; // doing it like this will put it in different columns
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900