// I want to read from a file and split each line by comma
// after splitting push those words into a vector and then display vector.
// I tried this code below but did not work as I expected. My text file is
// given under the code.
// My expected output is this
// Hamidur
// Rahman
// MAC
// 125
// MAC
// 190
// MAT
// 231
// Thanks advance.
I have to disagree with Thomas about the "first problem" -- it is not:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#include <iostream>
#include <string>
#include <sstream>
int main ()
{
std::string line = "foo,bar,gaz";
std::stringstream ss(line);
std::string name;
while ( getline( ss, name, ',') ) {
std::cout << "# " << name << " #\n";
}
return 0;
}
# foo #
# bar #
# gaz #
The getline ( ss, line, ',') reads up to a comma or end-of-stream, whichever comes first. The word after the last comma is a valid read.
The real issue is the way the data is printed from the vector, like Thomas said.
C++11 has a ranged for syntax that is ideal for this purpose.
A traditional loop is okay too, if written correctly.
I did ask you to describe what did happen, because one can usually realize the problem self when trying to tell it to others. That is important part of programming.