C++ code error with getline(Cin,string)

Asked

Viewed 1,138 times

0

I’m learning to program in C++ and when I use the getline function(Cin,name) I can’t put text in there and the Avanca code for the next line. The program should ask for age and name and is supposed to have an output that indicates the age and name placed in the input. Can someone help me? Thank you

#include <iostream>
#include <string>

using namespace std;

int main()
{
    int age;
    cout << "Insere a tua idade: ";
    cin >> age;

    string nome;
    cout << "Insere o teu nome: ";
    getline(cin, nome);

    cout << "Ola " << nome << "! Segundo a tua resposta tens: " << age << " anos" << endl;

    return 0;
}

1 answer

0


When you enter the cout << "Insere tua idade: " he’s going to pass the \n ( enter) to the cin >> age;

In turn it will be the first character read by getline(cin, nome); so this line is skipped. Do this to solve this problem:

cout << "Insere o teu nome: ";
while(getline(cin, nome))
   if(nome != ""){
          break;
    }

There are other possibilities of clearing the buffer using the Cin.ignore.

I recommend reading: How to handle the use of getline() in a for(;;)?

  • Thank you very much solved my problem!

  • I think I ask something a bit stupid but what does "getline(Cin, name)" mean. How is that a condition?

  • @kikolaranjo excuse the delay! Remember this: "no doubt is stupid". Basically it is pq C++ interprets while(0) AS FALSE and the other numerals and characters are interpreted as TRUE! This question will resolve your question: What is while(0) and while(1) in C?

  • If the answer helped you, Tour

  • Thanks again. It helped me a lot!

Browser other questions tagged

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