Joh*_*ohn 2 c++ string stringstream type-conversion
是否有可能像这样串流?我试着用ifstream读取并转换它.
string things = "10 11 12 -10";
int i1;
int i2;
int i3;
int i4;
stringstream into;
into << things;
into >> i1;
into >> i2;
into >> i3;
into >> i4;
Run Code Online (Sandbox Code Playgroud)
我希望它是:
i1 = 10
i2 = 11
i3 = 12
i4 = -10
Run Code Online (Sandbox Code Playgroud)
那是对的吗?
可以多次使用相同的stringstream变量吗?
当我尝试时,第一次没问题,但其他一切都只是0.
那肯定会奏效.您甚至可以混合类型,如下所示:
string things = "10 Nawaz 87.87 A";
int i;
std::string s;
float f;
char c;
stringstream into;
into << things;
into >> i >> s >> f >> c; //all are different types!
cout << i <<" "<< s <<" "<< f <<" "<< c;
Run Code Online (Sandbox Code Playgroud)
输出:
10 Nawaz 87.87 A
Run Code Online (Sandbox Code Playgroud)
在ideone上演示:http://www.ideone.com/eb0dR