getline() a string giving difficulty

前端 未结 3 563
逝去的感伤
逝去的感伤 2020-12-22 13:00

i am doing a task where i am inputting ist no of times you want to have input and then i am inputting a full line by the use of getline but sime how i am not able to do that

3条回答
  •  [愿得一人]
    2020-12-22 13:37

    You are mixing formatted input and unformatted input functions.

    operator>> leaves the trailing newline after the number you extracted in the input buffer, but this isn't a problem for subsequent reads done with operator>> because it skips all the whitespace it finds before reading. On the other hand, getline reads until it finds the delimiter (\n by default) without skipping anything.

    Long story short: if you want to use getline you have to clean the buffer from the \n after your cin>>test;:

    #include 
    // ...
    
    cin>>test;
    cin.ignore(numeric_limits::max(), '\n');
    

提交回复
热议问题