我制作了一个程序,应该将输入内容打印出来。然后运行一个简单的加法运算,但是当我在输入中使用空格时,它将跳过加法运算。我不知道问题是什么。
这是班级的东西
#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
}
[...]
};
并且主要变成:
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();
通常,将标准输入作为类的接口的一部分读取是个坏主意,因为将来很难重用该类(例如,使用从文件而不是从人那里获取输入的程序)。安慰)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句