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;
}