C++ csv file reading

  • #1

Main Question or Discussion Point

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:

Answers and Replies

  • #2
rcgldr
Homework Helper
8,682
520
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().
 
  • #3
thanx i solved it using a simple stringstream conversion...I guess i was sleepy last night when i was doing this part :D
 

Related Threads on C++ csv file reading

Replies
6
Views
8K
  • Last Post
Replies
7
Views
73K
  • Last Post
Replies
9
Views
3K
Replies
2
Views
758
Replies
2
Views
20K
  • Last Post
Replies
1
Views
2K
Replies
13
Views
709
Replies
11
Views
30K
Replies
3
Views
2K
  • Last Post
Replies
3
Views
2K
Top