|
Use C++ <sstream> library to convert datas
We learned stringstream class in C++<sstream> library, it seems that there are not so many students attach importance to this useful tool to settle difficulties in practice.
Now I show an example of converting string type variable to int type variable.
// convert string type to int type // if the string is illegal, the int type remain its last value #i nclude <iostream> #i nclude <sstream> using namespace std;
int main() { string str; int num = 0; stringstream sstrm; while(cin >> str) { sstrm << str; sstrm >> num; sstrm.clear(); sstrm.str(""); cout << "the string is " << str << endl; cout << "get number " << num << endl; } return 0; }
We can use << and >> operator to transfer data flow conveniently, but just remember each time when the transfermation is performed, the inner states of a stringstream object will be changed, so we use clear member function to reset the states. It's not enough, because the clear function doesn't mean "clear the memory"! We should use another function str() and use "" parameter to clear the memory immediately.
Now let me show another example, to convert int type variable to string type variable.
// convert int type to string type #i nclude <iostream> #i nclude <sstream> using namespace std;
int main() { string str; int num = 0; stringstream sstrm; while(cin >> num) { sstrm << num; sstrm >> str; //sstrm.clear(); sstrm.str(""); cout << "the string is " << str << endl; cout << "get number " << num << endl; } return 0; }
You'll see that the str() member function is not used, because string type accepts any legal characters, but int type just accepts from '1' to '9'.
When you input a letter, the program will terminate, because the cin object will set a bad state and return false in (cin >> num) expression.
阅读全文 | 回复(0) | 引用通告 | 编辑
|