I am trying to do a .txt file parser for a game project. I want the parser to look through each line in the text file and if that line contains a comma signs divide that line by those commas.
example.txt:
1 2 3
a
b,c
d,e,f
c++ code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
std::ifstream file;
file.open("example.txt");
if (file.is_open())
{
std::string line;
std::stringstream sline;
std::string var;
while (std::getline(file, line))
{
sline << line.c_str();
while (std::getline(sline, var, ','))
{
std::cout << var << std::endl;
}
}
file.close();
}
Output when running:
a
Wanted output:
1 2 3 4 5 6
a
b
c
d
e
f
What am I doing wrong, and are there better ways to achieve the wanted output?
Just because you don't get errors doesn't mean your program is correct. You should read and understand documentation for these standard functions before you use them.
A std::stringstream is designed to work with a std::string. So when you use a C-string to create the stringstream the compiler converts the C-string into a std::string. Since you already had a std::string you are doing an operation that is not needed and wastes CPU cycles.