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

Asked

Viewed 1,800 times

10

I was fixing the white space problem with the getline only that I came across this problem where the question "Type the employee name:" is skipped, how to solve this?

Is it because I’m using cin and getline in the same program? Because only with the cin << nomeFuncionario; I don’t have this problem.

inserir a descrição da imagem aqui

            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;
  • I think this reading is essential for those who are starting in c++ and want to understand a little more about data input and output. https://pt.wikibooks.org/wiki/Programar_em_C%2B%2B/Entrada_e_sa%C3%ADda_de_dados

2 answers

6


Where have you got this:

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

Place this, to run that line while it is not filled.

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

The alternation between >> and getline should be done carefully, as the edge should be followed by the end of the input line.

Another option would be the use of ignore after the expression:

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

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

5

After using cin with the extractor << should be used cin.ignore(1000,'\n') to remove the \n left in the buffer associated with reading the values entered on the keyboard (not to read inadvertently empty strings in the hypothetical following 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;
}
  • 1

    Use the ignore is recommended but sometimes it discards other things too.

  • 1

    @Edilson How so?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.