cin>> not work with getline()

后端 未结 2 1645
长情又很酷
长情又很酷 2020-12-12 06:20
#include 
#include 
using namespace std;

int main () {
  string str;
  int age;
  cout << \"Please enter age: \";
  cin>>a         


        
相关标签:
2条回答
  • 2020-12-12 07:04

    getline() won't work with an int, or any number for that matter. It is defined as such:

    istream& getline (char* s, streamsize n );
    
    istream& getline (char* s, streamsize n, char delim );
    

    So, it takes in strings and char*'s; not digits.

    0 讨论(0)
  • 2020-12-12 07:06

    You still have a newline in the stream after cin>>age;, which is giving you an empty string for the name.

    You could solve it by just adding another getline() call after getting the age and throwing away the result. Another options is to call cin.ignore(BIG_NUMBER, '\n');, where BIG_NUMBER is MAX_INT or something.

    0 讨论(0)
提交回复
热议问题