C++主题:将"getline"与"If If else"结合使用

C++ topic: Using "getline" in conjunction with "If If else"

本文关键字:If else 结合 getline 主题 C++      更新时间:2023-10-16

我有一个关于使用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从输入流中读取字符并将它们放入字符串中。

因此,只有当变量yourAgestd::string时,getline()才会起作用。对于阅读intstd::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()将它们转换为整数。