Weird behaviour with std::getline and std::vector

前端 未结 3 1786

I have the following code:

std::vector final_output;
std::string input;

int tries = 0;
std::cin >> tries;

int counter = 0;
while(count         


        
相关标签:
3条回答
  • 2021-01-29 04:41

    When you enter the number for tries, you hit the return key. After you read tries, the carriage return from hitting the return key is still sitting in the input buffer. That carriage return will normally be translated to a new-line character. Your next call to getline reads everything in the input buffer up to the next new-line. Since the first character is a new-line, it reads that as a line of zero length (i.e., zero characters before the new-line).

    0 讨论(0)
  • 2021-01-29 04:55

    The newline of the first entry is still in the input buffer.

    You can call std::cin.ignore(); just after reading tries from cin.

    This way the newline gets discarded.

    I found a good link that explains plenty of things regarding the use of I/O:

    • http://www.augustcouncil.com/~tgibson/tutorial/iotips.html
    0 讨论(0)
  • 2021-01-29 04:58

    You have nothing to absorb the '\n' from the first line in your standalone std::cin >> tries.

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