C++主题:将"getline"与"If If else"结合使用
C++ topic: Using "getline" in conjunction with "If If else"
我有一个关于使用getline和If/Else-If语句的问题。
目前,我的代码如下:
int yourAge = 13;
cout << "What's your age dude? ";
if(yourAge < 21) {
cout << "What? " << yourAge << "? You're too young to drink!!! " << endl;
} else if(yourAge >= 21) {
cout << "Cool!" << yourAge << "? You are good to go. Don't drink and drive!" << endl;
}
return 0;
}
这很好用。你的年龄是13岁,结果是上面写着"你太年轻了,不能喝酒"。
但是,我想在代码中引入getline函数,以便结果取决于用户的输入。我试图更改代码如下:
int yourAge;
cout << "What's your age dude? ";
getline(cin, yourAge);
if(yourAge < 21) {
cout << "What? " << yourAge << "? You're too young to drink!!! " << endl;
} else if(yourAge >= 21) {
cout << "Cool!" << yourAge << "? You are good to go. Don't drink and drive!" << endl;
}
return 0;
}
反过来,每当我试图编译时,就会出现以下错误消息:
"ctut.cpp: In function ‘int main()’:
ctut.cpp:25:25: error: no matching function for call to ‘getline(std::istream&, int&)’
getline(cin, yourAge);
^
ctut.cpp:25:25: note: candidates are:
In file included from /usr/include/wchar.h:90:0,
from /usr/local/include/c++/4.9.2/cwchar:44,
from /usr/local/include/c++/4.9.2/bits/postypes.h:40,
from /usr/local/include/c++/4.9.2/iosfwd:40,
from /usr/local/include/c++/4.9.2/ios:38,
from /usr/local/include/c++/4.9.2/ostream:38,
from /usr/local/include/c++/4.9.2/iostream:39,
from ctut.cpp:1:
/usr/include/stdio.h:442:9: note: ssize_t getline(char**, size_t*, FILE*)
ssize_t getline(char ** __restrict, size_t * __restrict, FILE * __restrict) __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_4_3);....."
这只是一个开始,它会持续很长一段时间。
如有任何关于如何修改的帮助,我们将不胜感激。我想获得关于用户年龄的用户输入,并根据输入在屏幕上吐出正确的消息。
谢谢!
引用cppreference.com,
getline
从输入流中读取字符并将它们放入字符串中。
因此,只有当变量yourAge
是std::string
时,getline()
才会起作用。对于阅读int
,std::cin
是绰绰有余的。
如果出于任何原因必须使用"getline()",则必须将字符串转换为int:
int yourAge;
string age;
cout << "What's your age dude? ";
getline(cin, age);
yourAge = stoi(age);
if(yourAge < 21) {
cout << "What? " << yourAge << "? You're too young to drink!!! " << endl;
} else if(yourAge >= 21) {
cout << "Cool!" << yourAge << "? You are good to go. Don't drink and drive!" << endl;
}
return 0;
getline()
用于读取字符串而非整数。你最好用cin>>yourAge;
做这个程序。阅读这些链接以了解有关getline link1 link2 的更多信息
您可以使用getline()
读取整数,但这是不可取的。最好使用cin
读取整数。
如果您想使用getline()
读取整数,请不要忘记使用stoi()
将它们转换为整数。
相关文章:
- 我的简单if-else语句是如何无法访问的代码
- 如何删除peer if else分支中的冗长句子
- 我似乎对if/else的基本语句有问题:/
- 使用if-else将数字转换为单词
- 为什么这个案例陈述需要一个"if else"而不仅仅是一个"if"?
- C++ If/Else 语句被跳过
- 如果条件不相关,我应该更喜欢两个 if 语句而不是 if-else 语句吗?
- 如何将 if else 语句重写为 switch 语句
- 在 C++ 中的 if-else if- else 语句期间更改变量
- 为什么我的 if else 语句不起作用并从数组中输出正确的索引?
- 我的 If Else 语句无法在向量 (C++) 中提供最大值
- 具有嵌套 if-else 的循环的时间复杂度
- 为什么无论输入如何,所有 if-else 语句都会打印?
- 简化对两个布尔值的 4 个 if/else 检查
- 如何在C++中创建 if else 循环而不是多个嵌套?
- 为什么切换 if else 语句的顺序会导致错误?
- 如何使用 if else 语句
- if/else 语句输出由于加号或减号而未显示正确的消息
- 如何解释 #if/#else 位域?(VC++菜鸟)
- if-else 语句仅按特定顺序工作,我不知道为什么