每当我在字符串中使用cin和空格时,为什么它只是跳过整个东西

Whenever i use cin and use spaces in the string, why does it just skip through the whole thing?

本文关键字:为什么 字符串 空格 cin      更新时间:2023-10-16

我编写了一个程序,它应该接受输入并打印出来。然后运行一个简单的加法,但是当我在输入中使用空格时,它会跳过加法。我不知道是什么问题。

这是类的东西

#include <iostream>
#include <string>
using namespace std;
class Cheese {
    private:
        string name;
    public:
        void setName(string x){
            cin >> x;
            x = name;
        }
        string getName(){
            return name;
        }
        void print(){
            cout << name << endl;
        }
};

这是主要的东西

int main()
{
    string h;
    Cheese hole;
    hole.setName(h);
    hole.getName();
    hole.print();

如果不让我输入

这部分就被跳过了
    int x = 5;
    int y = 16;
    cout << x+y;
    num(x);
    int a;
    int b;
    int c;
    cout << "Type in a number and press enter.";
    cin >> a;
    cout << "Repeat.";
    cin >> b;
    c = a+b;
    cout << c << endl;
    if(c <= 21){
        cout << "Good job!";
    }
    else {
        cout << "You fail!";
    }
    return 0;   
}

我建议你们把职责划分得稍微不同一点。Cheese类的setName函数应该简单地接受一个字符串,并将实例的成员变量设置为给定的参数。

然后你的程序可以从标准输入中读取并在main中填充字符串,并将该字符串传递给setName

更具体:

class Cheese {
    private:
        string name;
    public:
        void setName(const string& x){
           // change this code to set the 'name' member variable
        }
        [...]    
};

main变为:

int main()
{
    string h;
    Cheese hole;
    std::string input_name;
    cout << "Type a name and press enter.";
    cin >> input_name;  // Will read up to first whitespace character.
    hole.setName(input_name);
    hole.getName();  // this is a no-op: compiler may warn of unused return value
    hole.print();

一般来说,读取标准输入作为类接口的一部分是一个坏主意,因为它使将来难以重用该类(例如,从文件而不是从控制台的人那里获取输入的程序)。

传递给cin输入流的输入将跳过任何空白、制表符或换行符。如果你想输入字符串,那么你可以使用cin.getline(string s)。空格后的输入被传递给下一个等待cin,因为下一个cin接受整数并得到一个字符串,所以它会跳过它。因此,当输入带有空格的字符串时,程序将跳过其余部分。