我想获取用户输入并将其输出到我的 shell 环境中

i want to take a user inputs and output it in my shell environment

本文关键字:输出 我的 shell 环境 获取 用户 输入      更新时间:2023-10-16

我想获取用户输入并将其输出到屏幕上。我假设让用户输入他们需要哪种类型,例如类型 O,但我的输出没有捕获我的 O,只是我的类型 ,那么有没有办法让它只捕获类型内的整行?

我的代码的示例输出。

输入太阳 类型:键入 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;

只读取一个单词,这就是为什么它停在 TypeO 之间的空格。

尝试使用gets() / getline()函数。 默认情况下,cincout忽略空格。我不知道如何让他们接受空格。但是使用上述功能,您将获得所需的结果。

参考: gets(), getline()

相关文章: