I am writing this program for my programming class and it has a bunch of stupid constraints like I must use nested if else statements and I have to use the cin.getLine() to get a players name. It is supposed to grab the name of each player and calculate their batting average.
This is not the entire program but up to the part where I am having an error. When I run this in a command prompt I can recieve the first name fine, but after that the second cin.getline() does not read any input. Suggestions?
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
char name1[100], name2[100], name3[100];
int numBat, numHit;
double avg1, avg2, avg3;
// Get Average for Player 1
cout << "What's Your Name? ";
cin.getline(name1, 100);
cout << "How many times have you been at bat? ";
cin >> numBat;
if(numBat < 0 || numBat > 25)
{
cout << "ERROR ::: Number of Times at Bat Cannot Be Less Than 0 or Greater Than 25. Run Program Again." << endl;
return 0;
}
else
{
cout << "How many times have you hit the ball? ";
cin >> numHit;
if(numHit < 0)
{
cout << "ERROR ::: Number Hit Cannot Be Less Than 0. Run Program Again." << endl;
return 0;
}
else
{
// Calculate Average for Player 1
avg1 = numHit / numBat;
// Get Average for Player 2
cout << "What's Your Name? ";
cin.getline(name2, 100);
cout << "How many times have you been at bat? ";
cin >> numBat;
cout << "How many times have you hit the ball? ";
cin >> numHit;
}
}
}
I think it's a buffer problem. Try to flush the cin before the second getline:
cin.clear(); // clear the buffer
cin.sync();
if that does not work, try something like this:
cin.ignore(256, '\n'); // ignore the endline and char(256)
After the getline, you need to output a newline using cout << endl;.
When you use
cin >> numBat;
It doesn't read the newline, so the next cin.getline() will read that and continue.
Use
cin >> numBat;
cin.ignore(80,'\n');
Related
I am writing a code for class that asks the user to input a size that is an odd number equal to or greater than 7. I have been able to make that part of my code work successfully. However, the next part consists of asking the user to enter a specific letter, in this case 'c'. If they do not enter 'c' then the loop should ask them to input another character. Whenever I run this code, it is creating an infinite loop whether I enter 'c' or another letter. I think my expression in my second while loop is incorrect, but I haven't been able to find a lot of information regarding this that could help me.
#include <iostream>
using namespace std;
int main() {
int s, l;
cout << "Welcome to the letter printer." << endl;
cout << "Enter the size: " << endl;
cin >> s;
while (s < 7 || s%2==0 || s<0)
{
cout << "Invalid size. Enter the size again: " << endl;
cin >> s;
}
cout << "Enter the letter: " << endl;
cin >> l;
while (l != 'c')
{
cout << "Invalid letter. Enter the letter again: " << endl;
cin >> l;
}
return 0;
}
because you are getting char for int variable
wrong:
int s, l;
right one:
int s;
char l;
what is why it goes on infinite loop in second while
explanation for infinite loop
This is how basic_istream works. In your case when cin >> l gets
wrong input - failbit is set and cin is not cleared. So next time it
will be the same wrong input. To handle this correctly you can add
check for correct input and clear&ignore cin in case of wrong input.
incorporated from here
I have this snippets of code from my original long program, and as much as it looks simple, it doesn't work correctly! I am brand-new to c++ language, but I know in Java that would be the way to do it (Regardless of the syntax).
Simply put, this should ask the user for an input to answer the following multiplication (5*5), however, it should also check if the user entered a wrong input (not number), keep asking the user again and again... Somehow, it keeps running forever without taking a new input!!
I hope to get, not only an answer, but also a reason for such an error!
int main() {
int userAnswer;
bool isValidAnswer = true;
cout << 5 << " * " << 5 << " = ";
cin >> userAnswer;
cin.ignore();
do {
if (cin.fail()) { //user input is not an integer
cout << "Your answer is not valid! Please enter only a natural number: ";
cin >> userAnswer;
cin.ignore();
} else {
isValidAnswer = false;
}
} while (isValidAnswer);
return 0;
}
Well you need to clear the error state before accepting new input. Call cin.clear() then cin.ignore() before trying to read input again.
I would do something like.
cout << "Enter a number: ";
cin >> number;
while(cin.fail())
{
cin.clear();
cin.ignore(1000, '\n'); //some large number of character will stop at new line
cout << "Bad Number Try Again: ";
cin >> number;
}
First, cin.fail() is not going to adequately check if your answer is a natural number or not with the type set to int (could also be negative).
Second, your boolean isValidAnswer is really checking if it's is an invalid answer.
Third (and most importantly), as another answer suggests, you should put in cin.clear() to clear the failure state, and then followed by cin.ignore(), which will remove the failed string from cin.
Fourth, cin will only check if an int exists somewhere in the string. You'll need to perform your own string comparison to determine if the entire input is a int (see answer below, based on this answer).
Updated:
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
bool isNum(string line)
{
char* p;
strtol(line.c_str(), &p, 10);
return *p == 0;
}
int main() {
int userAnswer;
string input;
bool isInvalidAnswer = true;
cout << 5 << " * " << 5 << " = ";
while (isInvalidAnswer) {
if (!(cin >> input) || !isNum(input)) {
cout << "Answer is not a number! Please try again:\n";
cin.clear();
cin.ignore();
}
else {
userAnswer = atoi(input.c_str());
if (userAnswer < 0) { //user input is not an integer
cout << "Answer is not a natural number! Please try again:\n";
} else {
isInvalidAnswer = false;
}
}
}
cout << "Question answered!\n";
return 0;
}
I've constructed a simple program that is supposed to take an amount in cents that the user inputs and outputs it in the form of dollars and cents, however, when I run it, it asks me for the amount, I input it, and the program doesn't proceed. I'm new to programming and would dearly appreciate any help I can get on the matter
#include <iostream>
using namespace std;
int main()
{
int numb;
int dollars=0;
int cents=0;
cout << "Enter the amount" << endl;
cin >> numb;
while (numb>=0);
{
dollars=int(numb/100);
cents=numb%100;
}
cout << dollars << "dollars" << cents << "cents"<<endl;
return 0;
}
The code below should work as you expected.
Read the comments I inserted into your code for more information.
Also, you may want to insert extra check in the loop for invalid input (i.e. non-digit characters) as that will cause the loop to enter an infinite loop.
EDIT: I've updated the code with the extra check to handle invalid non-numeric user input.
#include <iostream>
using namespace std;
int main()
{
int numb = 0;
int dollars=0;
int cents=0;
cout << "Enter the amount" << endl;
// I suspect your while loop here is to keep soliciting input
// if the input is not valid, so I've moved the "cin" into the loop.
// Don't use semi colon here after the while statement because
// in doing so, you're eliminating the body of the loop.
while (numb <= 0)
{
cin >> numb;
if(cin.fail()) {
cin.clear();
cin.ignore(numeric_limits<int>::max(), '\n');
cout << "Non numeric input, please try again." << endl;
continue;
}
cout << "numb: " << numb << endl;
dollars=int(numb/100);
cents=numb%100;
}
// I've inserted extra spaces around dollars and cents here
// to make the output more readable.
cout << dollars << " dollars " << cents << " cents"<<endl;
return 0;
}
This while loop doesn't make any sense. Remove it.
while (numb>=0); // remove this line and the '{' '}'
{
dollars=int(numb/100);
cents=numb%100;
}
Generally when using loops check that they will terminate. You are checking every iteration that numb>=0 but inside the loop numb never changes it's value. So the program executes this loop forever.
You have an infinite loop with your 'while' block, because numb is always positive (it doesn't change for any iteration).
Try removing the while loop to let the program proceed.
#include <iostream>
using namespace std;
int main()
{
int numb;
int dollars=0;
int cents=0;
cout << "Enter the amount" << endl;
cin >> numb;
dollars=int(numb/100);
cents=numb%100;
cout << dollars << "dollars" << cents << "cents" << endl;
return 0;
}
You can also have a look at other answers that give you ways to use a loop to repeatedly ask for (valid) user inputs.
you made an infinite loop
while (numb>=0);
{
dollars=int(numb/100);
cents=numb%100;
}
numb is let's say 3, so this always 3>=0 equals true therefore, you neverexit that loop
I have an issue with the code in line 23. (Please see code below)
When I use "cin >> studentNum"; I have no issue and the program reads the one string for the firstname, but if I want to gather more data using "getline(cin, studentNum)" to read more strings like the full name, the program just skips the command and asks for the score .
Why is that?
#include <iostream>
#include <string>
using namespace std;
int main()
{
int studentNum, testNum, i, j;
double sum, testScore, average;
string studentName;
i = 0;
// asking user for input
cout << "Please enter the number of students in this classroom: " << endl;
cin >> studentNum;
cout << "Now enter the number of tests each student has taken in this class: " << endl;
cin >> testNum;
while (i < studentNum)
{
cout << endl << "Now please enter the firstname of the student: " << endl;
cin >> studentName; //**My Problem is in this line ###########**
j = 0;
sum = 0;
while (j < testNum)
{
cout << "Please enter the score of each test, then hit enter: " << endl;
cin >> testScore;
sum += testScore;
j++;
}
i++;
}
}
It sounds to me that you need to use cin.ignore. You need to discard the linefeed character still present in the stream.
#include <limits>
// This is not a C++11 feature, works fine in C++98/03
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::getline(std::cin, studentName);
By default, operator>> will skip leading whitespace, i.e. classifed by std::ctype. You can see that in a test program by turning this behavior off with unsetf(std::ios_base::skipws), that it will extract the whitespace. By using cin.ignore, you can simply discard it since it's undesirable. For more information, see cin and getline skipping input.
You should clear the state flag and flush the steram
cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
getline(cin, studentName);
I'm trying to get the user to input their name(s) using a while loop with an array and cin, but after the last person's name is input, the program crashes instead of moving on. Is there a way to fix this, or do I need to completely change up the code? I'm also fairly new to c++, so can any answers be given as simply as possible?
#include <iostream>
#include <string>
using namespace std;
int main()
{
unsigned int numberofplayers;
number://loop back here if more than 4 players
cout << "Number of players: ";
cin >> numberofplayers;
if(numberofplayers > 4 || numberofplayers < 1){
cout << "Invalid number, please enter a number from 1 to 4." << endl;
goto number;
}
string name[numberofplayers];
cout << "Enter your name" << endl;
int a = 1;
while(a < numberofplayers + 1){
cout << "Player " << a << ": ";
cin >> name[a];
cout << "Hello, " << name[a] << "." << endl;
a++;
}
}
You would probably facing array index out of bound, so Change you while loop to this and set a=0 to fill from 0th index.
while(a < numberofplayers){
}
Your last iteration exceeds the size of the array. You need to change it to
while(a < numberofplayers)
also, on another note, the keyword goto isn't used much anymore. I would suggest using a while there also like
while(true){
cout<<"number of players";
cin>>numberofplayers
if(numberofplayers is valid input){
break;
}
cout<<"bad input";
}
There is a question on stackoverflow discussing the use of goto extensively here:
GOTO still considered harmful?