Hello all.

I'm trying to read a line of data in from a csv file and then assign the fields to it to an int w, string y, and double z **See code below**


However, I have two problems:

1. The first is in reading in the all contents of the second field and assigning it to a string y WITH white-space included. If I compile this code it will only output the first word in the second field even with the noskipws **line 36**

2. The second is reading in the complete number with both decimal places (only the 12 shows) and assigning it to a double z **lin 42**

For simplicity sake the contents of file "clients.txt" read are:

503,long meadow,12.29

But the output to screen is:

503 long 12

#include <cstdlib>
#include <fstream>
#include <ios>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
#include <sstream>

using namespace std;

int main()
{
	
	int w;
	string word;
	string y;
	double z;

	ifstream infile("clients.txt");

	while (getline( infile, word ))
	{
	  if (word.empty()) continue;

	  istringstream ss( word );

	  { string val;
		getline( ss, val, ',' );
		stringstream( val ) >> w;
		cout<<"	"<<w<<"	";
		}

	  { string val;
		getline(ss,val, ',' );
		stringstream( val )>>noskipws>> y;
		cout<<y<<"	";
		}

		{ string val;
		getline( ss, val, ',' );
		stringstream( val ) >> z;
		cout<<z<<endl;		
		}

	}

	system("PAUSE");

	return 0;

}

1) line 36: you don't need that line because line 35 has has already assigned val all the words including spaces .

You can use stringstream to convert from std::string to int or float, but I find it more convenient (in most cases) to just use atol() and atof(). There are problems with using those two functions, but if you KNOW the file contains no errors and the numbers are in normal range then there should be no problems using them. If there are some problems with the values in the file then you should use stringstream so that you can capture errors better.

#include<iostream>
#include <sstream>
using namespace std;

int main()
{
    std::string word = "503,long meadow,12.29";
    int w;
    float z;
    string val;

    stringstream ss(word);
    getline(ss,word,',');
    w = atol(word.c_str());
    cout << w << "\n";
    getline(ss,word,',');
    cout << word << "\n";
    getline(ss,word,',');
    z = (float)atof(word.c_str());
    cout << z << "\n";
}

lines 28, 34 and 40. Don't declare val in each of those blocks. Just declare it once at the begining of the function and reuse it everywhere in your program. Its also not necessary to block out those like you did on lines 28 and 32.

This article has been dead for over six months. Start a new discussion instead.