Reading char and string in c ++

-1

I have to put an integer, a real, a character and a sentence containing spaces up to 100 characters. I tried to make the solution but I can only type the numbers and the character and the string are not coming out.

#include<iostream>
#include<iomanip>

using namespace std;

int numero;
float real;
char carac;
string frase;

int main(){

    cin>>numero;
    cin>>real;
    cin>>carac;
    getline(cin,frase);



    cout<<numero;
    cout<<fixed;
    cout.precision(6);
    cout<<real<<carac<<frase<<endl;
    
asked by anonymous 06.09.2018 / 20:14

1 answer

1

The problem is that getline gets the last line break that was made with:

cin>>carac;

And so it does not even allow you to type anything.

A simple solution is to consume the line break you've been using cin.ignore() :

cin >> numero;
cin >> real;
cin >> carac;
cin.ignore(); // <-- consumir aqui antes do getline
getline(cin,frase);

See working on Ideone (set couts to be easier to read)

Remember that you can either chain readings in cin or cout by simplifying the code. The same applies to fixed and precision or setprecision . That's why your code can only be:

cin >> numero >> real >> carac;
cin.ignore();
getline(cin,frase);

cout << numero << fixed << setprecision(6) << real << carac << frase << endl;
    
06.09.2018 / 23:31