Nested Getline in text file parser

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?
Why are you using the c_str() function? Also you probably need to clear() the stream errors at the end of the loop.

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
#include <iostream>
#include <string>
#include <sstream>

int main()
{
   // Emulate a file stream.
   std::string fileContents = "a,b\nc,d,e\nf\n";
   std::stringstream file(fileContents);
   
   std::stringstream sline;
   std::string var;
   std::string line;
   while (std::getline(file, line))
   {
      sline.str(line);  // Replace the contents of the stream.
      while (std::getline(sline, var, ','))
      {
         std::cout << var << std::endl;
      }
      // Clear any stream errors. 
      sline.clear();
   }
   return(0);
}
Thank you very much!

I don't really know why I used c_str() .. It didn't give any visual error so I just used it.
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.



Topic archived. No new replies allowed.