【发布时间】:2015-02-19 06:23:29
【问题描述】:
我有一个关于使用 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);....."
这只是开始,会持续很长一段时间。
任何关于如何修改的帮助将不胜感激。我想获取用户年龄的用户输入,并根据输入在屏幕上吐出正确的消息。
谢谢!
【问题讨论】:
-
getline(cin, yourAge);不会工作,除非yourAge是std::string。关键是您要解析每行数据吗? -
对不起 WhozCraig,我不认为我正在尝试解析每行数据。我只是一个初学者,正在尝试编写一些东西,让我能够以用户身份输入数据,并根据我的输入输出不同的文本。
标签: c++ if-statement getline