std::getline() reads wrong data after reading formatted input from stream

前端 未结 2 1645
礼貌的吻别
礼貌的吻别 2021-01-06 11:46

I looked at some other questions and I\'m too newbish at C++ to know if they applied to my question here..

Basically when show the output of \"name\", if I type in

2条回答
  •  南方客
    南方客 (楼主)
    2021-01-06 12:04

    The problem is that formatted input using >> reads a value and stops once the value is completely parsed. For example, a number is completed once something not matching the format appears. That is, the reading would stop right in front of a space or a newline (and quite a few other characters). Normally these extra characters don't cause an problems because formatted input starts off with skipping leading whitespace (space, tab, newline, etc.) before attempting to read the actual value.

    However, unformatted input, e.g., getline() starts to read its value immediately and stops once it encounters a newline (or the character specified as the newline character if the three argument version is used). That is, getline() would immediately stop after reading the newline character if that is left in the stream.

    The easiest way to get rid of the newline character (and any other leading whitespace) is to use std::ws, e.g.:

    if (std::getline(std::cin >> std::ws, name)) {
        ...
    }
    

    ... and, BTW, whenever you attempt to read something you should always check after reading that the attempt to read the value was successful!

    Another approach is not to use std::getline() at all and instead just use the formatted input for the name, too. However, that assumes that there isn't any space in the name.

提交回复
热议问题