Hi guys, I am new with c++, so please bear with me...

I am reading in a text file that similar to this:


I need to be able to place each number in a variable like:

B = 12345
C = 12345

I can get the delimiter to read the first variable but I am having problems using getline() to make the rest variables. Any help would be appreciated. Thanks!

8 Years
Discussion Span
Last Post by kreskin

One way you to solve this is to read char by char. maybe something like
this :

char ch;
string content;
ifstream iFile("file.txt");

while( iFile.get(ch) )
      if(ch != ',')
          content += ch;
          content = "";

Assuming there are no blank spaces, and all the data is on one line (no newlines in the data before the end)...you can use the comma as the delimiter in getline( ) to read in the text, then get your numeric values and ignore the commas, like so:

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

int main( )
	char str[10];
	int a, b;

	cin.getline( str, 10, ',' );
	cin >> a;
	cin.ignore( );
	cin >> b;

	cout << str << "  " << a << "  " << b << endl;

	return 0;

My keyboard input for this is:

Replace the "cin" with your file handle, it works the same.

Edited by vmanes: n/a


I ended up doing it character by character. Since I had to do some editing to the characters when i had separated them into individual strings.
Thanks for the help ideas!

comma1 = line.find(',');
			comma2 = line.find(',',comma1+1);
			comma3 = line.find(',',comma2+1);
			time = line.substr(comma1+1,comma2-comma1-1);
			lat = line.substr(comma2+1,comma3-comma2-1);
			NS = line.substr(comma3+1,comma4-comma3-1);

that is a cut example of how i got the answer.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.