How to convert data read using getline in C++ to numerical values?
In C++, you can utilize the std::getline function to read string data and convert it to numerical types using other methods. Here is an example:
#include <iostream>
#include <string>
#include <sstream>
int main() {
std::string input;
std::cout << "输入一个数字:";
std::getline(std::cin, input);
// 使用std::istringstream将字符串转换为数值类型
std::istringstream iss(input);
int number;
if (iss >> number) {
std::cout << "转换后的数值为:" << number << std::endl;
} else {
std::cout << "无法转换为数值类型" << std::endl;
}
return 0;
}
In the example above, we first use the std::getline function to read a line of string data from standard input. Then, by creating a std::istringstream object, we pass the read string data to it. Next, we use the >> operator to extract the data from the std::istringstream object and try to convert it to an int type. If the conversion is successful, we output the converted value; otherwise, we output an error message.
Please note that you need to include the