How would I implement this line in C++
scanf("%lf, %lf, %lf", &a, &b, &c)
ie: I want to get file data input that is separated by commas
How would I implement this line in C++
scanf("%lf, %lf, %lf", &a, &b, &c)
ie: I want to get file data input that is separated by commas
Solution 1:
std::cin >> a;
std::cin.ignore();
std::cin >> b;
std::cin.ignore();
std::cin >> c;
ignore()
ignores a single character.
Solution 2:
Use a dummy variable for the comma:
char comma;
std::cin >> a >> comma >> b >> comma >> c;
char comma1, comma2;
if (file_stream >> a >> comma1 >> b >> comma2 >> c &&
comma1 == ',' && comma2 == ',')
...a b and c read & parsed successfully...
else
...error...
Remy Lebeau comments below that he thinks the functionally equivalent code below is easier for beginners to understand - I disagree but readers can make up their own mind:
char comma1, comma2;
file_stream >> a >> comma1 >> b >> comma2 >> c;
if (!file_stream.fail() && (comma1 == ',') && (comma2 == ','))
...a b and c read & parsed successfully...
else
...error...
If your "file data" is arriving on stdin
as you've indicated in a comment, you can replace file_stream
above with std::cin
. If you want to use an actual file stream:
if (std::ifstream file_stream(filename))
if (file_stream >> a >> ...as above...
Alternatively, this old answer codes up a Str
class that allows usage like this:
if (file_stream >> a >> Str(",") >> b >> Str(",") >> c)
...a b and c read & parsed succesfully...
Do you want to read data from file instead of standard stream? Then use fscanf