Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

C++ csv file reading

  1. Sep 6, 2012 #1
    I am trying to read from a csv file, the file looks like below:
    1,2,3
    4,5,6
    7,8,9
    0


    I used getline(Input_file,size,',') but the problem with this is that it seems to see the numbers not separated by commas as one string., for the code below i was expecting the following output:

    1
    debug
    2
    debug
    3
    debug
    4
    debug
    5
    debug
    6
    debug
    7
    debug
    8
    debug
    9
    debug
    0
    debug

    I tried to modify the program to look for and eof but it couldnt work....

    my code looks like below:

    if(input_file.good()){

    while(!input_file.eof()){

    input_file.getline(number,256,',');//number is an array of characters... i.e char number[10]


    cout<<number<<endl;
    cout<<"debug:\n";}}/*note that after the debug word only one number is supposed to be printed but instead I get:
    1
    debug
    2
    debug
    3 -----> expecting a debug word between 3 and 4
    4
    debug
    5
    debug
    6 -----> something wrong here, expecting a debug word between 6,7
    7
    debug
    8
    debug
    9 --->clearly something wrong expecting a word between 9,0
    0
    debug
    */

    I can't figure out what i am doing wrong, can anyone help me debug my code and a better way of doing what i am trying to do.
     
    Last edited: Sep 6, 2012
  2. jcsd
  3. Sep 6, 2012 #2

    rcgldr

    User Avatar
    Homework Helper

    Your getline() parameter for the terminator is a ',' but the last number on each input line is not followed by a ','. You could use input_file.getline(buffer, sizeof(buffer)) ... which defaults to newline '\n' as the terminator, but then you'd have to parse the lines, probably using sscanf().
     
  4. Sep 6, 2012 #3
    thanx i solved it using a simple stringstream conversion...I guess i was sleepy last night when i was doing this part :D
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: C++ csv file reading
  1. Textread of csv-file (Replies: 9)

  2. Csv reader (Replies: 1)

Loading...