How to remove comma from input file?

I have this problem that require some help..

I am making a program that reads data from a .txt file.
Each data is seperated by a ,
Example: XXX, XXX, XXX, XXX
However, if the data is a string type then it will read the , too whcih is not
what i wanted..
How can I remove it before assigning it?
You can read the whole line from the file into a string by using std::getline and then

1) replace all occurences of the comma with the space character;
2) use std::istringstream to read each data in a string by using std::getline( is, s, ',' ), where is - std::istringstream object, s - std:;string

For example

1
2
3
4
5
6
7
8
9
{
	std::string s( "XXX, XXX, XXX, XXX" );
	std::istringstream is( s );

	std::string t;

	while ( std::getline( is, t, ',' ) ) std::cout << t << ' ';
	std::cout << std::endl;
}


The output of the code snip is
XXX XXX XXX XXX


Another example of substituting the comma for the space

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
{
	std::string s( "XXX, XXX, XXX, XXX" );


	std::cout << s << std::endl;

	std::string::size_type n = 0;

	while ( ( n = s.find( ',', n ) ) != std::string::npos )
	{
		s.replace( n, 1, 1, ' ' );
		n++;
	}

	std::cout << s << std::endl;
}
Last edited on
thanks.. but how do i break them up? as in

string s = " ccc, aaa, bbb";
int a;
float b;
string c;

what method can i use to assign each of them into different datatype?
I think there is no problem to assign a string to another string. As for data of types int and float then there are such functions as stoi and stof
Here is an example of one of possible realizations

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
29
30
{
	std::string s( " string, 10, 123.456, c" );

	std::cout << s << std::endl;

	std::string::size_type n = 0;

	while ( ( n = s.find( ',', n ) ) != std::string::npos )
	{
		s.replace( n, 1, 1, ' ' );
		n++;
	}

	std::cout << s << std::endl;

	std::istringstream is( s );

	std::string item1;
	int item2;
	float item3;
	char item4;

	is >> item1 >> item2 >> item3 >> item4;

	std::cout << "item1 = " << item1
		  << ", item2 = " << item2
		  << ", item3 = " << item3
		  << ", item4 = " << item4
		  << std::endl;
}


The output of the code snip is

string, 10, 123.456, c
string 10 123.456 c
item1 = string, item2 = 10, item3 = 123.456, item4 = c
Last edited on
Topic archived. No new replies allowed.