C++ getline method not working

前端 未结 4 1985
借酒劲吻你
借酒劲吻你 2021-01-24 23:41

I\'m sorry but I\'m quite new to C++ but not programming in general. So I tried to make a simple encryption/decryption. However when I added the modification to my previous code

相关标签:
4条回答
  • 2021-01-24 23:51

    Use :

    cin.ignore ( std::numeric_limits<std::streamsize>::max(), '\n' );

    to eat newlines from previous input std::cin >> op;

    header - <limits>

    Other way would be :

        while (std::getline(std::cin, str)) //don't use string
        if (str != "")
        {
           //Something good received
    
            break;
        }
    
    0 讨论(0)
  • 2021-01-24 23:54

    That's because std::cin >> op; leaves a hanging \n in your code, and that's the first thing getline reads. Since getline stops reading as soon as it finds a newline character, the function returns immediately and doesn't read anything more. You need to ignore this character, for example, by using cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); (std::numeric_limits is defined in header <limits>), as stated on cppreference.

    0 讨论(0)
  • 2021-01-24 23:58

    This is because you still have the newline character in the buffer which makes getline() stop reading as soon as it encounters it.

    Use cin.ignore() to ignore the newline character from the buffer. This will do in your case.

    In general, if you want to remove characters from your buffer untill a specific character, use:

    cin.ignore ( std::numeric_limits<std::streamsize>::max(), ch )
    
    0 讨论(0)
  • 2021-01-25 00:09

    As other stated already, the formatted input (using in >> value) start skipping space abd stop when they are done. Typically this results in leaving some whitespace around. When switching between formatted and unformatted input you typically want to get rid of leading space. Doing so can easily be done using the std::ws manipulator:

    if (std::getline(std::cin >> std::ws, line)) {
        ...
    }
    
    0 讨论(0)
提交回复
热议问题