3
When I run this code it Buga, i type 1 and it enters the registration function but not pause to read the data (keeps printing things non-stop)when I change the cin
for scanf
it works). You can make it work with the Cin command?
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<iostream>
using namespace std;
typedef struct {
char nome[100];
}pessoa;
pessoa a[100];
int c=0;
void cadastro();
void imprimi();
void cadastro(){
std::cout<<"Digite o nome:"<<endl;
cin.get(a[c].nome,100);
c++;
}
void imprimi(){
cout<<"\n\n\n";
for(int i=0;i<c;i++){
std::cout<<"Nome:"<<a[i].nome<<endl;
std::cout<<"------------"<<endl;
}
}
main(){
int op=0;
while(op!=3){
std::cout<<"\n\t---IMC---"<<endl;
std::cout<<"1-Cadastrar usuario:"<<endl;
std::cout<<"2-Listar usuarios:"<<endl;
scanf("%d",&op);
fflush(stdin);
switch(op){
case 1:
cadastro();
break;
case 2:
imprimi();
break;
case 3:
exit(1);
break;
default:
std::cout<<"digite um numero valido"<<endl;
break;
}
}
}
First thing: why mix C code with C++? I don’t even know if I want to mess with a code all mixed up.
– Maniero
Hello, Matheus. Welcome. You have undefined behavior in the first line of the registration function (
fflush(stdin)
). I don’t know who taught you this, but it’s wrong. Your code is really big and messy. Please create a [mcve] that displays the problem.– Pablo Almeida
I tested your program. I entered the data in the format Cin expects, I used a dot instead of a comma. It worked. Then I tested it again and when I entered the height using comma the result was the behavior you talked about. It is complicated to use Cin to read data because you have no control over what the user will type and depending on the input you can not predict the behavior. I haven’t written command line programs in c/c++, but if I were to use Cin.getline to make sure I read the whole line, then something to convert the string to the format I want, sscanf is an option.
– user49056
reduced the code(still plays the same problem),tried Cin.getline and n changed nothing(when scanf use it works). has how to do works using Cin?
– Matheus Lima
here when I test with Cin it n to receive the values
– Matheus Lima
Which compiler are you using?
– user49056