gpt4 book ai didi

C++ 主题 : Using "getline" in conjunction with "If If else"

转载 作者:行者123 更新时间:2023-11-30 00:49:16 25 4
gpt4 key购买 nike

我有一个关于将 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;

}

这很好用。 yourAge 是 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 reads characters from an input stream and places them into a string.

因此,只有当您的变量 yourAgestd::string 时,getline() 才会起作用。对于读取 intstd::cin 就足够了。

关于C++ 主题 : Using "getline" in conjunction with "If If else",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28599875/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com