Can I use "cin" and "getline" in the same code?

10

I was fixing the whitespace problem with getline , but I got this problem where the question "Enter the employee name:" is skipped, how do I solve this?

cout<<"\n\nDigite o nome da empresa: ";
            getline (cin,nomeEmpresa);      

            cout << "\n\nNúmero de funcionários: " ;
            cin >> n;

            cout << "\n\nDigite o nome do funcionário: ";
            getline (cin,nomeFuncionario);

            cout << "\n\nDigite o número de horas trabalhadas: ";
            cin >> horasTrabalhadas;
    
asked by anonymous 13.12.2015 / 15:51

2 answers

6

Where you have this:

cout << "\n\nDigite o nome do funcionário: ";
getline (cin,nomeFuncionario); 

Place this to run this line until it is filled.

cout << "\n\nDigite o nome do funcionário: ";
while(getline(cin, nomeFuncionario))
  if(nomeFuncionario != ""){
  break;
} 

Switching between >> and getline must be done with care, as the end of the input line end must be followed.

Another option would be to use ignore after expression:

while (isspace(cin.peek()))
{ 
    cin.ignore();
}

In most cases it is recommended to use ignore after >> to discard the new line, but depending on the situation you can also discard non-white content. Cases where the total integrity of the data received is not of extreme importance.

    
13.12.2015 / 16:22
5

After using cin with << extractor, cin.ignore(1000,'\n') must be used to remove \n left in the buffer associated with reading values entered on the keyboard (not to read inadvertently empty strings in the following hypothetical readings).

#include <iostream>
using namespace std;

int main(){

    int i;
    string nome;

    cout << "Digite um inteiro:";
    cin >> i;
    cin.ignore(1000,'\n'); // Experimente remover esta linha para ver o resultado
    cout << "Digite o seu nome: ";
    getline(cin, nome);

    return 0;
}
    
13.12.2015 / 23:43