How do they work: String streams
Dec 8, 2009 at 12:55pm UTC
Hi,
I've been breaking my head over this for quite a while now and can't figure out how and even more important why this code works.
this is the input file:
1 word1 2
2 word2 3
3 word3 4
this is the output file:
word1 1 2
word2 2 3
word3 3 4
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
#include <fstream>
#include <iostream>
#include <sstream>
#include <iomanip>
#include <string>
using namespace std;
int main(void )
{
ifstream infile("infile.str" );
if (infile)
{
char buffer[81];
cout<< endl << "file information:" << endl;
while (infile.getline(buffer, 81, '\n' ))
{
istringstream instr(buffer, istringstream::in);
int number1, number2;
char word[50];
instr>> number1 >> word >> number2;
cout<< word << setw(10) << number1 << setw(10) << number2 << endl;
}
}
else cerr<< endl << "Error opening: infile.str" ;
infile.close();
return 0;
}
I'm having trouble understanding how this line works:
instr>> number1 >> word >> number2;
Is it defaul behavior for the >> operator to have a space character being the spacing character?
What if I would be working with a csv file, so the seperator for the field would be a "," ? Could I accomplish splitting a line into variables using the above method?
Dec 8, 2009 at 1:01pm UTC
Dec 8, 2009 at 1:11pm UTC
So say that I have the same input file, except the seperator is a comma. Would this code be correct to get the values into seperate variables?
1 2 3
instr.getline(number1, sizeof (int ), ',' );
instr.getline(word, 50, ',' );
instr.getline(number2, sizeof (int ), ',' );
I suppose the rest of the code is still correct.
Dec 8, 2009 at 1:16pm UTC
Just found out I had to use reinterpret_cast<char *>
Is this the way to go ? or should I stay away from reinterpret_cast ?
Dec 8, 2009 at 1:20pm UTC
You should read to a string, create a new stringstream and read the integer
eg:
1 2 3
string numb_str;
getline ( instr, numb_str, ',' );
stringstream ( numb_str ) >> number1;
-You can also do that via C strings-
Topic archived. No new replies allowed.