c++ - stringstream 中的自定义字符串输入

标签 c++ stream c++14 stringstream

我正在编写一个程序,它接受一个字符串,并从该字符串中提取三个数字。下面的代码使用预定义的字符串显示工作程序。我似乎无法弄清楚如何从用户那里获取字符串。我试过 stringstream iss(str) 在 main 函数中声明字符串,但这没有用。

#include<iostream>
#include<string.h>
#include <sstream>
using namespace std;
int main()
{
    int T,j;
    int X,Y,K;
    string s;
        stringstream iss("134 513 515");
    cin>>T;
    for(int i=0;i<T;i++)
    {
        iss>>X>>Y>>K;
        cout<<X<<endl<<Y<<endl<<K<<endl;
        int count=((X+Y)/K);
        if(count%2==0)
        cout<<"Chef ";
        else
        cout<<"Paja ";

    }
    cin>>j;
    return 0;
}

最佳答案

您可以使用 getline 读取字符串,然后将其传递给 stringstream :

#include<iostream>
#include<string.h>
#include <sstream>
using namespace std;
int main()
{
    int T,j;
    int X,Y,K;
    string s;
    cin>>T;
    cin.ignore();
    for(int i=0;i<T;i++)
    {
        getline(cin, s);
        stringstream iss(s);
        iss>>X>>Y>>K;
        cout<<X<<endl<<Y<<endl<<K<<endl;
        int count=((X+Y)/K);
        if(count%2==0)
        cout<<"Chef ";
        else
        cout<<"Paja ";

    }
    cin>>j;
    return 0;
}

不要忘记 cin.ignore()cin>>T; 之后刷新 cin 缓冲区

关于c++ - stringstream 中的自定义字符串输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56990466/

相关文章:

c++ - GCC `-fsanitize=bounds` `std::array` 的奇怪行为

c# - 需要双冲吗?

C++14类函数错误: "Object has no attribute ' value'"

c++ - 缩短作为模板参数传递到 CRTP ("pass me"中的长模板派生类)

c++ - RValues 的初始化列表

c++ - 如何仅使用 SSE2 对 double/int 进行 floor/int?

c++ - 使用指向压缩结构成员的指针时出现编译器警告

javascript - 使用 Javascript 在新窗口中打开 PDF 流

C++ 创建一个对象并在同一行中使用它

d3.js - Bluemix Kafka 流