-4

Non-working code:

#include<iostream>
#include<fstream>
#include<string>
int main(){
int id; string name;char comma ; double money;
ifstream read("testfile.csv");
 while (read >> id >> comma>> name >> comma >> money)
 {cout << id <<comma<<name<<comma<<money<<  endl ;}
 read.close();
 _getch();
return 0;}

The csv file data & structure:

1,user1,999 2,user2,33 3,user3,337

But, the following works fine. Why so?

while (read >> id >>comma>>name) {cout << id<<comma<<name <<endl ;}

1 Answers1

3

When you read a string using >>, it reads a space delimited string. If there is no space in the text you read, it will read until the end of the line (as newline is a space).

Because of this the "parsing" of the input will after a little while be out of sync with the contents from the file, and will lead to an error when attempting to read one of the numbers.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • +1 -- where to find/learn the following info? **When you read a string using >>, it reads a space delimited string** **as newline is a space** – CowardlyDog Feb 22 '17 at 15:47
  • @CowardlyDog For most information I usually go to [this reference wiki](http://en.cppreference.com/w/cpp). The [input/output reference](http://en.cppreference.com/w/cpp/io) have of course a section on [`std::basic_istream`](http://en.cppreference.com/w/cpp/io/basic_istream) (which is the base class for all input streams) which in turn have links to the [in-class member `operator>>` overload](http://en.cppreference.com/w/cpp/io/basic_istream/operator_gtgt) as well as the [non-member `operator>>` overloads](http://en.cppreference.com/w/cpp/io/basic_istream/operator_gtgt2) (used for strings). – Some programmer dude Feb 22 '17 at 15:59
  • 1
    @CowardlyDog [Continued...] For reading strings, the last reference contains the text "The extraction stops if one of the following conditions are met: ...a whitespace character ... is found." Ergo, reading strings is space-delimited. :) – Some programmer dude Feb 22 '17 at 16:00