Use Sstream to complete the conversion,
1#include <iostream>2#include <string>3#include <sstream>4#include <stdint.h>5 6 intMain ()7 {8STD::stringStr_integer;9 uint64_t integer;Ten One std::getline (std::cin, Str_integer); A Std::stringstream SS; - ss.str (Str_integer); -SS >>integer; theStd::cout << __line__ <<":"<< integer <<Std::endl; - - return 0; -}
A one-time conversion is easier, but if the Std::stringstream object is used more than once, you should pay attention to state cleanup.
1#include <iostream>2#include <string>3#include <sstream>4#include <stdint.h>5 6 intMain ()7 {8STD::stringStr_integer;9 uint64_t integer;Ten Std::stringstream SS; One AStr_integer ="1234"; - ss.str (Str_integer); -SS >>integer; theStd::cout << __line__ <<":"<< integer <<Std::endl; - -Str_integer ="12345"; - ss.str (Str_integer); +SS >>integer; -Std::cout << __line__ <<":"<< integer <<Std::endl; + A return 0; at}
You will find that the value of the second output is not 12345, but 1234.
The reason is that after the first SS >> Integer is executed, the SS is placed on the EOF flag, so the second time the SS >> Integer is executed, it is not output, and the original 1234 is retained in the integer. The following code can be executed correctly,
#include <iostream>#include<string>#include<sstream>#include<stdint.h>intMain () {std::stringStr_integer; uint64_t integer; Std::stringstream SS; Str_integer="1234"; Ss.str (Str_integer); SS>>integer; Std::cout<< __line__ <<":"<< integer <<Std::endl; Str_integer="12345"; Ss.str (Str_integer); Ss.clear (); //Plus, it's going to be the right output.SS >>integer; Std::cout<< __line__ <<":"<< integer <<Std::endl; return 0;}
Ss.clear () can clear the EOF flag, and SS >> integer will output correctly.
In addition, if you want to clear stringstream data, use the following method to ensure the correct execution,
Ss.str (""); // resets buffer data ss.clear (); // not necessary, but for the sake of insurance.
So we found that in many places the use of Ss.str ("") follow-up did not get the correct output, it is likely that the status flag is not cleared, and the use of Ss.clear () alone is not up to the purpose of clear buffer data, is wrong.
C + + string to Integer