我想获取用户输入并将其输出到我的屏幕上。 我想让用户输入他们需要什么样的类型,例如 Type O ,但是我的输出没有捕获我的 O ,只是我的 Type ,那么有没有办法让它只捕获 Type 内的整行?
我的代码的示例输出。
输入太阳类型:k
输入行星:10
输入的太阳类型:类型
行星数量:10
这只是我整个冗长代码的一部分。
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
class LocationData
{
private:
string sunType;
int noOfEarthLikePlanets;
int noOfEarthLikeMoons;
float aveParticulateDensity;
float avePlasmaDensity;
public:
};
int main()
{
int i;
string s;
LocationData test;
cout<<"Enter Sun Type: ";
cin>>s;
test.setSunType(s);
cin.clear();
cin.ignore(10000,'\n');
cout<<"Enter planets: ";
cin>>i;
test.setNoOfEarthLikePlanets(i);
cout<<"Sun type that was entered: "<<test.getSunType();
out<<"\nNo of Planets: "<<test.getNoOfEarthLikePlanets()<<endl;
}
最佳答案
是
getline(cin, s);
读取整行并将该行放入 s
变量中。正如你所发现的
cin >> s;
只读一个单词,这就是为什么它会停在 Type 和 O 之间的空格处。
关于c++ - 我想接受用户输入并在我的 shell 环境中输出它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12914080/