stringstream into 4 variables without comma
I am struggling to figure out why the first data item is not appearing
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
#include <algorithm>
#include <string>
#include <iostream>
#include <sstream>
int main() {
int c_id{0};
std::string c_last;
double c_discount{0.0};
float w_tax{0.0};
std::stringstream data {"1,zzz,0.09,10.0"};
data >> c_id >> c_last >> c_discount >> w_tax;
std::cout << c_last << " " << c_discount << " "<< w_tax << "\n";
return 0;
}
| |
the output from the above is:
As you can see, the "1" is missing.
In addition, why are there additional zeros appearing on the end ?
Well, you aren't outputting c_id on line 16, so there won't be a 1.
The rest of the string is going into c_last (as there are no whitespaces, but it's the only way you are going to retain commas).
Then c_discount and w_tax don't get any new values, so they stay as 0 and get output as such.
Try:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
#include <algorithm>
#include <string>
#include <iostream>
#include <sstream>
int main() {
int c_id{0};
std::string c_last;
double c_discount{0.0};
float w_tax{0.0};
std::stringstream data {"1 zzz 0.09 10.0"}; // <===== use spaces, not commas
data >> c_id >> c_last >> c_discount >> w_tax;
std::cout << c_id << " " << c_last << " " << c_discount << " "<< w_tax << "\n"; // <=== output c_id as well
return 0;
}
| |
Last edited on
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 31 32 33 34 35 36 37 38 39 40 41
|
#include <string>
#include <iostream>
#include <sstream>
int main() {
{
int c_id{0};
std::string c_last;
double c_discount{0.0};
float w_tax{0.0};
std::stringstream data {"1,zzz,0.09,10.0"};
data >> c_id >> c_last >> c_discount >> w_tax;
std::cout << c_id << " / "
<< c_last << " / "
<< c_discount << " / "
<< w_tax << "\n";
}
{
int c_id{0};
std::string c_last;
double c_discount{0.0};
float w_tax{0.0};
std::stringstream data {"1,zzz,0.09,10.0"};
char ch;
data >> c_id >> ch;
getline(data, c_last, ',');
data >> c_discount >> ch >> w_tax;
std::cout << c_id << " / "
<< c_last << " / "
<< c_discount << " / "
<< w_tax << "\n";
}
}
| |
1 / ,zzz,0.09,10.0 / 0 / 0
1 / zzz / 0.09 / 10 |
Topic archived. No new replies allowed.