首页 > 解决方案 > 无法使用 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 只会输出为零。我究竟做错了什么?

标签: c++stringstream

解决方案


``
#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.

推荐阅读