我正在编写一个程序,它接受一个字符串,并从该字符串中提取三个数字。下面的代码使用预定义的字符串显示工作程序。我似乎无法弄清楚如何从用户那里获取字符串。我试过 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/