When reading a stream from the command line into a variable using std::getline does not allow entering data, jumps. How can I read a string with spaces in a variable by avoiding my problem in std::getline

 std::string fio; std::string citi; int id; std::cout << "Введите id(число) абонента: "; std::cin >> id; std::cout << "Введите ФИО абонента: "; std::getline(std::cin, fio, '\n'); std::cout <<"Введите город абонента: "; std::cin >> citi; 

CONCLUSION:
add subscriber to user group

 Введите id(число) абонента: 12 Введите ФИО абонента: Введите город абонента: 

    3 answers 3

    Insert line

     #include <limits> //... std::cout << "Введите id(число) абонента: "; std::cin >> id; std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' ); std::cout << "Введите ФИО абонента: "; std::getline(std::cin, fio, '\n'); 

    The problem is that in the input buffer, after using operator >> remains a newline character corresponding to the pressed Enter key. And the std;:getline function reads the buffer until this character is encountered. Therefore, if it is not removed, an empty string will be read.

    • Works thank you) - Ghost

    Because after entering the number, the character '\n' remains in the buffer. It is read when entering a string as an empty string. You need to flush the contents of the buffer before entering the line:

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

    If you enter a number incorrectly, you must also clear the error status flag cin.clear() .

       (std::cin >> id).get(); 

      It is necessary to ignore the newline character, because it remains and then getline reads until it encounters this character and eventually an empty line is read.

      • I have a problem at this point std :: getline (std :: cin, fio, '\ n'); - Ghost