Read char and string in c++

Asked

Viewed 1,260 times

-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 it is not leaving the character and the string.

#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;
  • And why are you mixing C with C++? Why don’t you do everything in C++?

  • because only with one can’t read separately. I had to do so

  • Of course it does, and it’s right, creating new complications doesn’t solve the problem. Try to solve it the right way it’s easier.

  • beauty I put them all with Cin, but even when I finish gitar the acarctere a finaliza o progrma e nem le a string

1 answer

1


The problem is that the getline picks up the line break left in the last read made with:

cin>>carac;

And that’s why he won’t even let you type anything.

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

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

Watch it work on Ideone (adjusted the couts to be easier to read)

Remember that both can chain the readings on cin as in the cout simplifying the code. The same applies to the fixed and precision or setprecision. So your code can stay just:

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

cout << numero << fixed << setprecision(6) << real << carac << frase << endl;

Browser other questions tagged

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