csv format - PROBLEM - What I'm I missing?
Mar 14, 2015 at 8:18pm UTC
I get a weird output from my CSV when entering data values on one line in the console.
What I'm I missing?
Expected: James Kai, 18.01.1996, London (in CSV file)
Actual: Jamesoai,L.01.1996,Lndon
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
using namespace std;
#include<iostream>
#include<string>
#include<iomanip>
#include<fstream>
int main(){
string first_name, last_name, dob, birth_place;
string file_name = "records.csv" ;
char comma, space;
ofstream input_to_file (file_name.c_str(), ios::out);
string title = "Records" ;
cout << title << endl << setfill('*' ) << setw(title.length()) << endl;
cout << "Enter data as shown below, seperate each value with a ','" << endl;
cout << "Example: James Kai, 18.01.1996, London" << endl;
cin >> first_name >> space >> last_name >>
comma >> space >> dob >>
comma >> space >> birth_place;
input_to_file << first_name << space << last_name <<
comma << dob <<
comma << birth_place << "\n" ;
cout << "Finished." << endl;
input_to_file.close();
cout << "Here is what you entered into " << file_name << endl << endl;
ifstream inFile;
inFile.open("records.csv" );
if (inFile.fail()){
cerr << "Error opening File" << endl;
exit(1);
}
string record;
while (!inFile.eof()){
inFile >> record;
}
cout << record << endl;
system("PAUSE" );
return 0;
}
Last edited on Mar 14, 2015 at 9:21pm UTC
Mar 14, 2015 at 9:22pm UTC
in your code you try to do
cin >> space
, but the >> operator skips whitespace, so this doesn't do what you think it does. For example, when you try to extract a space after the first name. What you actually get is the letter K from the last name. Also
cin >> comma
wont work either. When you have
this will be placed into the last name variable comma and all. The >> operator does not stop at the comma.
Last edited on Mar 14, 2015 at 9:23pm UTC
Mar 15, 2015 at 3:52pm UTC
What are the alternatives to account for the spaces and commas?
Mar 15, 2015 at 6:59pm UTC
std::noskipws /*and or*/ std::getline
http://www.cplusplus.com/reference/ios/noskipws/
Last edited on Mar 15, 2015 at 7:01pm UTC
Topic archived. No new replies allowed.