c++ - 无法使用 stringstream 读取 int 和 double
问题描述
#include <iostream>
#include <sstream>//for istringstream
int main(){
std::istringstream iss;
std::string tempSTR;
int A;
double B;
std::cout<<"Please enter an int.\n";
std::cin>>tempSTR;
iss.str(tempSTR);
iss>>A;
std::cout<<"A = "<<A<<"\n";
std::cout<<"Please enter a double.\n";
std::cin>>tempSTR;
iss.str(tempSTR);
iss>>B;
std::cout<<"B = "<<B<<"\n";
std::cout<<"\nEND OF PROGRAM. GOODBYE!\n\n";
}//end of main
代码很简单,但它就是行不通。我只需要使用一个字符串流来读取一个 int 然后是一个 double 。首先读取 int 是可行的,但 double 只会输出为零。我究竟做错了什么?
解决方案
``
#include <iostream>
#include <sstream>//for istringstream
//Using stringstream to read in multiple arguments
int main(){
std::istringstream iss;
std::string tempSTR;
int A;
double B;
std::cout<<"Please enter an int.\n";
std::cin>>tempSTR;
iss.str(tempSTR);
iss>>A;
iss.clear();
std::cout<<"A = "<<A<<"\n";
std::cout<<"Please enter a double.\n";
std::cin>>tempSTR;
iss.str(tempSTR);
iss>>B;
iss.clear();
std::cout<<"B = "<<B<<"\n";
std::cout<<"\nEND OF PROGRAM. GOODBYE!\n\n";
}//end of main
``
//Question:Unable to use stringstream to read in int and double
//Answer:stream just needed to be cleared before using it to read in another argument.
推荐阅读
- asp.net - 在 Xamarin.Forms 中使用 Web API
- reactjs - 用另一个对象过滤对象
- myob - MyOB AccountRight API | 更新客户的“特定”地址
- tensorflow - TensorFlow Serving 错误 - 找不到与提供的标签匹配的元图 def:{ serve }
- javascript - Redux-persist 集成问题
- google-app-engine-python - App Engine python柔性环境3.6还是3.7?
- chart.js - 在 chart.js 中,通过单击按钮更改图表颜色
- c# - 动态 SQL 的 SQL 端白名单是否存在问题?
- reactjs - 访问本地存储中的图像
- c# - 使用没有证书文件的 TLS 连接到 MariaDB