每当我在字符串中使用cin和空格时,为什么它只是跳过整个东西
Whenever i use cin and use spaces in the string, why does it just skip through the whole thing?
我编写了一个程序,它应该接受输入并打印出来。然后运行一个简单的加法,但是当我在输入中使用空格时,它会跳过加法。我不知道是什么问题。
这是类的东西
#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接受整数并得到一个字符串,所以它会跳过它。因此,当输入带有空格的字符串时,程序将跳过其余部分。
相关文章:
- 为什么字符串比较的 == 运算符相对于任一字符串长度线性时间(似乎)?
- 为什么字符串的 move() 会改变内存中底层数据的位置?
- 为什么字符串没有更新并且最终没有打印任何内容
- 为什么字符串类型会导致 c++ 程序无法运行?
- 为什么字符串流只读取整数中的第一个数字?如何使它只在空白处移动?
- C++ char 数组特征:为什么字符串在数组结束之前停止?
- 为什么字符串(常量字符* s,size_t pos,size_t len = npos)有效?
- 使用 String.resize() 后,为什么字符串的大小没有改变?
- 为什么字符串不会在堆栈中推送或弹出
- 为什么字符串的长度在第一次读取文件时相差 1?
- 为什么C++字符串迭代器不检查错误?
- 为什么字符串没有 cout 的输出
- C++为什么字符串的地址尽管是十六进制格式,但不能存储在 long int 变量中?
- 为什么字符串和 int 之间的 + 运算符充当 substr
- 为什么字符串变量"sum"不存储任何数据,程序不给出任何输出
- 为什么字符串文字不是prvalue
- 为什么字符串流>>失败时更改目标的值?
- 为什么字符串的第一个输入没有分配给 std::string 对象?
- 为什么字符串在函数参数中作为常量字符串传递
- 为什么字符串变量打印与垃圾