Dev C++ program closes immediately when entering letters - c++

My program closes immediately when I enter a letter. It shows the rest of the code but I do not get to enter the other parts of it. The program closes immediately when entering letters but remains when entering numbers, up until the part where the program is supposed to show the copied information. I have tried putting getchar(); after every cin<<a; but it skips lines and I only get to enter few info. Here is my code:
* I am an extreme newbie, this is by far the longest code I've ever worked on.
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string>
using namespace std;
int main()
{
string a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,y,z;
cout<<"Enter Your Name:";
cin>>a;
cout<<"Enter Your Gender:";
cin>>z;
cout<<"Enter Your Age:";
cin>>b;
cout<<"Enter Your Address:";
cin>>c;
cout<<"Enter Your School:";
cin>>d;
cout<<"Enter Your Nickname:";
cin>>e;
cout<<"Enter Highest Educational Attainment:";
cin>>f;
cout<<"What are your skills?:";
cin>>g;
cout<<"How many years experience do you have in this field?:";
cin>>h;
cout<<"What kind of people would you like to have in the workplace?:";
cin>>i;
cout<<"What good values do you have?:";
cin>>j;
cout<<"What bad values do you have?:";
cin>>k;
cout<<"When is your birthday?:";
cin>>l;
cout<<"What is your Father's name?:";
cin>>m;
cout<<"What is your Mother's name?:";
cin>>n;
cout<<"Do you have any children?:";
cin>>o;
cout<<"What is your eye color?:";
cin>>y;
cout<<"What do you dislike?:";
cin>>p;
cout<<"How many are you in the family?:";
cin>>q;
cout<<"What is your favorite food?:";
cin>>r;
cout<<"Your name is:"<<a<<endl;
cout<<"You are a:"<<z<<endl;
cout<<"You are"<<b<<cout<<"years old."<<endl;
cout<<"You live in:"<<c<<endl;
cout<<"You studied in:"<<d<<endl;
cout<<"Your nickname is:"<<e<<endl;
cout<<"Your highest educational attainment is:"<<f<<endl;
cout<<"Your skills are:"<<g<<endl;
cout<<"You have"<<h<<cout<<"years of experience in this field."<<endl;
cout<<"You would like to have"<<i<<cout<<"in the workplace."<<endl;
cout<<"The good thing is, you are:"<<j<<endl;
cout<<"The bad thing is, you are also:"<<k<<endl;
cout<<"Your birthday is in:"<<l<<endl;
cout<<"Your father is:"<<m<<endl;
cout<<"Your mother is:"<<n<<endl;
cout<<"You have"<<o<<cout<<"children."<<endl;
cout<<"You have"<<y<<"eyes."<<endl;
cout<<"You dislike:"<<p<<endl;
cout<<"You are"<<q<<cout<<"in the family"<<endl;
cout<<"Your favorite food is:"<<r<<endl;
return 0;
system ("pause");
}
*Edit: Replaced float with string and added #include <string> at the start of the code. The only problem now is the program closing when it is supposed to show the output and when entering a space in the input the next questions are in one line.

if x is a float type or an integer type
std::cin >> x;
reads no letter from std::cin if std::cin starts with a character that cannot be a prefix for a float or an integer type.
So x remains to 0 and your input stream remains unchanged.
For the next
std::cin >> y;
with y of type float or integer, the same behavior occurs: y remains to 0 and your input stream std::cin still starts with a character that cannot be read by a float or an integer type.
This behavior goes on until the end of your program.

float a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,y,z;
Variable a and other of type float. Which means they can store values like 1,10.0,12.3546 e.t.c. As soon as you enter any invalid character for this data type this program will exit.
If you want to run your program try declaring all variable as std::string and take input via getline like this getline(std::cin,var).
P.S : I have assumed here that var is of type string.

Related

error on do while loop condition in C++ with condition to continue the loop

I am making c++ program using do while loop but after inserting the condition while ( x =='y'|| x == 'Y'); I got an error where the loop is continued without letting me to insert the input again.
I can't insert the input until I stop the program.
#include <iostream>
using namespace std;
int main()
{
char str[30];
char symptom,quest;
char a,b,x,y,Y,n,N;
do{
cout<<" Enter your name: "<<endl;
cin.get(str,30);
cout<<"Hi " << str << ", Welcome to COVID test!"<<endl;
cout<<"Let's start the self testing test!"<<endl<<endl<<endl;
cout<<"########################################################"<<endl;
cout<<" COVID SELF TESTING CENTRE "<<endl;
cout<<"########################################################"<<endl<<endl;
cout<<"Do you have any symptoms below: (1-Yes, 2-No)"<<endl;
cout<<"Fever --> "<<endl;
cin>>a;
cout<<"Cough --> "<<endl;
cin>>a;
cout<<"Flu --> "<<endl;
cin>>a;
cout<<"Shortness of breath --> "<<endl;
cin>>a;
cout<<"Sore throat --> "<<endl;
cin>>a;
cout<<"Have you ever tested POSITIVE COVID-19 : "<<endl;
cin>>b;
cout<<"Do you had close contact with those who have been confirmed PORITIVE COVID-19 in the last 14 days? : "<<endl;
cin>>b;
cout<<"Do you have a history of traveling abroad or outside the state of Perak in the last 14 days? : "<<endl;
cin>>b;
cout<<"Are you currently undergoing a home quarantine control order by the Ministry of Health Malaysia? : "<<endl;
cin>>b;
cout<<endl<<endl;
cout<<"========================================================="<<endl;
cout<<" RESULT FOR COVID-19 SELF TESTING CENTRE "<<endl;
cout<<"========================================================="<<endl;
symptom=a;
quest=b;
if (symptom=='2'&&quest=='2')
{
cout<<"GREEN ZONE. Your status are low risk and no symptoms. Please folllow the SOP and Stay Safe Thank You!"<<endl;
}
if (symptom=='1'&&quest=='1')
{
cout<<"RED ZONE. Please get a clinically COVID-19 checkup from nearby hospital. Please folllow the SOP and Stay Safe Thank You!"<<endl;
}
if (symptom=='1'&&quest=='2')
{
cout<<"YELLOW ZONE. Please stay at home or self quarantine. Please folllow the SOP and Stay Safe Thank You!"<<endl;
}
if (symptom=='2'&&quest=='1')
{
cout<<"YELLOW ZONE. Please stay at home or self quarantine. Please folllow the SOP and Stay Safe Thank You!"<<endl;
}
cout<<"Ingin teruskan? (Y-yes, N-No): "<<endl;
cin>>x;
cout<<" ";
}while ( x =='y'|| x == 'Y');
system("pause");
return 0;
}
The problem you are seeing is that there is are leftover characters in the cin buffer, so the next time through the loop it reads those and doesn't ask the user for input. If you clear the buffer out at the end of the loop then the subsequent runs work.
do {
//...
std::cout << "Ingin teruskan? (Y-yes, N-No): "<< std::endl;
std::cin >> x;
std::cout << " ";
// add this to ignore and clear the current cin buffer
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
} while (x == 'y' || x == 'Y');
Have a look at this question for some more related details.
You may also need to add #include <limits> to use numeric_limits (although in my case iostream pulls it in so I do not need to add that include).

i don't know how to show output of code on graphic console in dev c++?

i want to show the output of code on graphic console in graphics.h. here is the code below that i want to show on graphic console
if(userinput == "1"){
cout<<"you choose addition\n";
cout<<"please enter your calculation : \n\n";
initwindow (600,600);
//creating rectangle
rectangle(40,70,410,290 );
cout<<"enter first number plzz:";
cin>>num1;
cout<<"enter sign of addition operator:";
cin>>mathop;
cout<<"enter second number";
cin>>num2;

Running as infinite loop [duplicate]

This question already has an answer here:
C++ Beginner Infinite Loop When Input Wrong Data Type and Help Evaluate My Code
(1 answer)
Closed 3 years ago.
When I try to call this function and provide a value to variable grade other than integer, the do-while loop kept on executing and don't even prompt for an input to the variable of type char. Kindly help me to figure out why loop kept on executing.
//User Input function
int userInput(){
int grade,question;
char choice='y';
srand(time(0));
do{
//displayMenu();
cout<<endl;
cout<<"Please select grades, use number 1 to 5: ";
cin>>grade;
/*if(grade<1 || grade>5){
cout<<"You have entered an invalid grade!"<<endl;
}
else{
cout<<"Enter number of questions you want to generate: ";
cin>>question;
while(question<1){
cout<<endl;
cout<<"You have entered an invalid number"<<endl;;
cout<<"Enter number of questions you want to generate: ";
cin>>question;
}
cout<<endl;
questionGenerator(grade,question);
cout<<endl;
cout<<"Press n/N to Quit or Press any key and then Enter";
cin>>choice;
system("cls");
}*/
cout<<"Type N/n to Quit or Press Any Key and then Enter"<<endl;
cout<<"Your choice? : ";
cin>>choice;
system("cls");
}while(choice!='n' && choice!='N');
return 0;
}
Well your grade variable is an intteger, so it cant take any other type of variable. If you are going to input a char then why is grade an integer or if you are going to inout a string? If you need this to be possible then maybe try using arrays and start turning them from arrays to: integers floats booleans strings or characters. Also be careful because a char value can be assigned to a number (character code).

how to check if inputed value is valid value in c++

I checked many links on Stack and to other site. Most of it does it what is supposed to do, but not "exactly" how I want to. Here is the problem and the best solution that i found on online.
I want to enter a number, float for example and input should be checked if is a float or not.
I'm using this snippet found online. Also to mention that i need to repeat validation each time for loop its iterated.The "n" is entered separately before this function and its in "private".It does its job perfectly, except ...If you enter "55" (number), it checks and validates. That's ok.
If you enter "dfgfd" stuff (not a number), it checks and repeats question. That's ok.
If you enter "dfgdfgdg55",it checks and repeats question. It's also ok. If you enter "55dfgfd" stuff, it checks and NOT repeats. That's NOT OK.It just discarding characters after numbers.I want to discard this also.So correct input should be JUST "55" entered.(Number 55 is just a example number entered when prompted).Also I tried this on a simpler function "model".First to enter "55", second to enter "55gdf". They been presented on screen as "55" and "55". Then i added some code afterwards to compare these numbers. They are not the same!
#include <iostream>
using namespace std;
int Provera_kucanja()
{
cout<<endl;
cout<<"Input boundary for an array"<<endl;
cin>>n;
while (cin.fail() || !(n>0))
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout<<"You didnt entered number, please try again... "<<endl;
cin>>n;
}
cout<<endl;
return 0;
}
float Unos_brojeva()
{
cout<<"\n";
cout<<"Now you must enter number into array:\n "<<endl;
for (int i = 0; i < n ; i++)
{
cout<<"Input "<<"["<<i<<"]"<<" number in array: ";
float r;
cin>>r;
while (cin.fail())
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout<<"You didnt entered number, please try again... "<<endl;
cout<<"Input "<<"["<<i<<"]"<<" number in array: ";
cin>>r;
}
unos[i]=r;
}
cout<<endl;
cout<<"Now show unsorted array members: "<<endl;
for(int i = 0; i < n; i++)
{
cout<<"This is "<<"["<<i<<"]"<<" member of array named 'unos': "<<unos[i]<<endl;
}
cout<<"\n"<<endl;
cin.get();
return 0;
}
int main(){
Provera_kucanja();
Unos_brojeva();
}
On the down side using suggested answers is that when user enters something like "ghfg" , result of this conversion is a ZERO!. So suggested answers is no-go's.
#include <iostream>
#include <algorithm>
#include <string>
#include <cstring>
using namespace std;
int main()
{
string A_number;
char* An_array=new char[A_number.length()];
cout<<"Enter value for A_number: ";
cin>>A_number;
strcpy(An_array,A_number.c_str());
float n=atof(An_array);
cout<<"Value entered is: "<<n;
cin.get();
return 0;
}
The line:
cin >> r
is going to try to read a valid float, even if there is bad trailing information after it.
You are saying the problem occurs when someone enters 55x, in this case you think it should not be considered a valid number.
There is an answer to your problem here: https://stackoverflow.com/a/19717896/312594
What you have to do is read the entire data in as a string and confirm that only characters that are possible as float input (digits, ., +, -, etc.) are in the input, and in the correct possible order. Only after you validate the input do you convert the input to float (via cin or some other mechanism).
In most cases you should accept 55x as 55 since that's probably what the user wants, but if you do want to be strict you have to perform the additional validation yourself.
p.s. - I almost hate to say this as I do not want to sound biased, but as you're learning C++ you may find it useful to write all of your code, including prompts, in English. If you later ask for help on StackOverflow, it will be easier for more people to understand what you are trying to do and therefore to help you out.
Sounds like you want to read in the input as strings (or possibly whole lines), and then you can test those strings any way you like.

How to Use real string types to represent strings within a function of a class structure?

I have been given a task of inputting some student data, like
option 1: Enter student name and id.
option 2: input i.d (verify against student id - input option 1), input upto 10 grades for the student and then calculating the average and letter grade for the student
option 3: output the student name, id and letter grade.
The program has to be written in a Class like structure - with declared variables and functions in the structure.
I have also been given the task for entering the details of 3 students using the Class structure. For simplicity sakes for now I am just writing a program for one student.
The program compiles O.K
First specific encountered problem: When I select option 'I' the program lets me input the student name and that's it! - skips the id input for some reason and continues on.
The problem is that I have been using cin>>and also scanf() as my main input methods - but these and system("Pause") have not been serving me well - I understand system("pause") is not very efficient. In the past I have been advised to use a real string type to represent strings like std::string class from the <string> library.
I would therefore appreciate any help with string classes so I can learn of them.
I believe there may be some other problems with my program but any advice with the string classes thing and my 'first specific encountered problem' would helpful to start of with.
So I have written the following program to represent my answer.
#include <iostream>
#include <cstdio>
#include <math.h>
using namespace std;
struct classroom{
char name;
int student_id;
float grades[10];
int num_tests;
float average;
float letter_grade;
void enter_name_id(void);
void enter_grade(int);
void average_grades(int);
void letter_grades(void);
void output_name_id_grade(void);
};
void classroom::enter_name_id(){
cout<<"\n Please enter name of student: \n"<<"\n";
cin>>name;
cout<<"\n Please enter student i.d number: \n"<<"\n";
scanf("%d",student_id);
cout<<"\n"<<student_id;
system("PAUSE");
}
void classroom::enter_grade(int n_tests){
if(n_tests<=10){
cout<<"\n Please enter student test grade: \n"<<"\n";
cin>>grades[n_tests];
}
else{
cout<<"\n You have reached your max number of grades entered!!"<<"\n";
}
system ("PAUSE");
}
void classroom::average_grades(int n_tests){
float sum=0;
int i;
for(i=0;i<n_tests;i++){
sum =sum+grades[i];
}
average=sum/(float)n_tests;
system ("PAUSE");
}
void classroom::letter_grades(void){
if(average>=90){
letter_grade=65;
}
if(average>=80&&average<90){
letter_grade=66;
}
if(average>=70&&average<80){
letter_grade=67;
}
if(average>=60&&average<70){
letter_grade=68;
}
if(average<60){
letter_grade=70;
}
system ("PAUSE");
}
void classroom::output_name_id_grade(void){
cout<<"\ Name I.D Grade "<<"\n";
cout<<name <<" ";
cout<<student_id<<" ";
cout<<(char)letter_grade<<"\n";
system ("PAUSE");
}
int main()
{
classroom a;
char option,answer,ans;
int a_num_tests, id;
a_num_tests=0;
for( ; ;){
cout<<"\nEnter 'I' for Name and I.d, 'G' for grades or 'O' for Data output "<<"\n";
cin>>answer;
switch(answer){
case'I':
a.enter_name_id();
break;
case'G':
cout<<"\n Please enter student i.d number: "<<"\n";
scanf("%d",id);
cout<<"\n"<<id;
if(id==a.student_id){
a_num_tests++;
a.enter_grade(a_num_tests);
cout<<"\n Would you like to enter another grade? 'Y' or 'N': "<<"\n";
cin>>ans;
while(ans=='y'||'Y'){
a_num_tests++;
a.enter_grade(a_num_tests);
cout<<"\n Would you like to enter another grade? 'Y' or 'N': "<<"\n";
cin>>ans;
}
a.average_grades(a_num_tests);
a.letter_grades();
}
else{
cout<<"\n You have entered the wong i.d number!!! \n"<<"\n";
break;
}
case 'O':
a.output_name_id_grade();
break;
default:
cout<<"\n Wong Entry "<<"\n";
break;
}
}
system ("PAUSE");
return 0;
}
Hi again for all those whom want to know, this code worked for me:
void classroom::enter_name_id(void){
cout << " Please enter your name\n>";
std::cin.ignore( 25, '\n' );
cin.getline( name,25);
cout << " Type id\n>";
cin>>student_id;
return;
}
Not sure how this line works: 'std::cin.ignore( 25, '\n' );'!!!
But never the less it was needed in order to prevent the compiler skipping
the next line: 'cin.getline( name,25);'
Originally I had problems with just using 'cin>>name' in the class function and this is why I have asked the questions for alternative real string types.
If anyone has more to add to this question, please do so.
I would like to say thank you again to all my fans out there whom have contributed to this progress we have made together.
Sail on...
So many things to say... why would you write << "\n" << "\n"?? You can just put the entire string in one piece, << "\n\n"... anyway.
For input/output, just stick with iostreams, and don't mix and match C library functions without good cause. Perhaps like so:
std::string name;
int id;
std::cout << "Please enter your name: ";
std::getline(std::cin, name);
std::cout << "Please enter the ID: ";
std::cin >> id; // see below
Maybe this answer is of some use to you. The input operations should be checked for errors, if you want to write serious code.
Note that token extraction (>>) reads word by word, so std::cin >> name will only read one single word. For something like a name, we prefer getline() for that reason.
If you run your program from the command line, you won't need all those system("pause") calls, either...
Update: It's not generally a good idea to mix token extraction (>>) with line reading (getline()), since the former doesn't gobble up newlines while the latter does. Best to stick to just one of the two, whichever is more appropriate for the input format.
If you only use line reading, you still have to process each line, perhaps again by token extraction. To do so, you need a string stream. Include <sstream> and replace the last line by:
std::string line; // you can put this at the top with the other declarations
std::getline(std::cin, line);
std::istringstream iss(line);
iss >> id;
scanf causes buffer problem. You need to clear the buffer after using it.
fflush(stdin). this will clear your buffer and input will stop for id and other inputs.
Also you can use getch() instead of system ("PAUSE");