Skips the first prompt instead [duplicate] - c++

This question already has answers here:
Why does std::getline() skip input after a formatted extraction?
(5 answers)
Closed 4 years ago.
Good day,
I was writing this code for a school project, but after compiling and executing it, after hitting yes, I was unable to enter a name.
I am not sure why this is happening, happened to both codeblocks and vs community.
I've tried adding cin.ignore(); below getline(cin, customer) and it kinda works but I am not able to enter the name of a business. If I put cin.ignore() on both, the enter number field will be skipped and it will go directly to the results.
I will attach an image below (without using cin.ignore)
#include "pch.h"
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
string input;
cout << "hello, press yes to start or no to cancel \n";
cin >> input;
if (input == "no")
{
cout << "have a nice day \n";
}
else if (input == "yes")
{
string customer;
string address;
int user_enter_number;
const double pc = 0.05 * 10;
double amount, abacus, price; // abacus = AMOUNT
time_t now; // rawtime
struct tm nowlocal;
cout << "Please enter your name " << endl;
getline(cin, customer); ` when executing, I was not able to type my
name and instead was skipped and went to
enter the store's name.`
cout << "Please enter the store's name \n";
getline(cin, address);
cout << "Please enter the number you would like to buy, the range is
from 00 - 99 \n";
cin >> user_enter_number;
cout << "Please enter the amount you wish to spend ($): \n";
cin >> amount;
abacus = amount * pc;
price = amount;
now = time(NULL); // obtains the time from the operating system
nowlocal = *localtime(&now);
cout << customer << " you have bought this number: " <<
user_enter_number << endl;
cout << "you have bought this pcs: " << amount / 0.05 << endl;
cout << "this ticket was bought on: " << nowlocal.tm_mday << "/" <<
nowlocal.tm_mon + 1 << "/" << nowlocal.tm_year + 1900 << endl;
cout << "at this time: " << nowlocal.tm_hour << ":" << nowlocal.tm_min << ":" << nowlocal.tm_sec << endl;
srand(time(NULL));
int min = 00;
int max = 99;
int num = (min + (rand() % (int)(max - min + 1)));
cout << "the winning number is: " << num << endl;
if (num == user_enter_number)
{
cout << customer << " You have won" << amount << "Please visit your
nearest store to collect! \n";
}
else
{
cout << "Try again next time! \n";
}
return 0;
}

The first line of input is a line. Use getline for that too.
cin >> input;
Leaves the newline in the buffer.
getline(cin, customer);
Only gets to read the newline from the first input.

Related

Error prompt when attempting to input a char into an int variable [duplicate]

This question already has answers here:
How to test whether stringstream operator>> has parsed a bad type and skip it
(5 answers)
How Can I avoid char input for an int variable?
(4 answers)
Closed 5 months ago.
I am trying to make an employee discount program that reads employee number and discount from an input file. I need it to display an error message when a character is put into the variable. I can't seem to figure this out. I'm a newbie so I don't know that many identifiers yet. This compiles with an unexpected output. I'm not sure how to get the variables for all three employees as well. Any help is greatly appreciated.
/* Program name: main.cpp
* Author: Carl Snyder
* Date last updated: 09/11/2022
* Purpose: Top employee discount calculator
*/
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
using namespace std;
int main()
{
ifstream inFile;
int winning_Num;
int employee_Num;
double total_Bill;
double discount_Percent;
double discount_Amount;
double bill_After_Discount;
inFile.open("EOM.txt");
inFile >> winning_Num >> discount_Percent;
cout << "Enter your employee number to see if you get a discount: ";
cin >> employee_Num;
cout << fixed << showpoint << setprecision(2);
if (employee_Num >= 10000 && employee_Num <= 99999)
{
if (employee_Num == winning_Num)
{
cout << "You have won a discount of " << discount_Percent << "%." << endl;
cout << "Enter the total bill: " << endl;
cin >> total_Bill;
if (total_Bill > 0)
{
discount_Amount = total_Bill * discount_Percent;
bill_After_Discount = total_Bill - discount_Amount;
cout << "Your discount will take $" << discount_Amount << " off your bill. "
<< endl;
cout << "Your new total is $" << bill_After_Discount << "." << endl;
return 0;
}
if (total_Bill <= 0)
{
cout << "The total should be greater than 0. The program will now
exit.";
}
else
cout << "You entered something that is not a number! The program will
now exit.";
}
else
cout << "Sorry you did not win a discount this month. Try again next
month.";
}
if (employee_Num <=9999 || employee_Num >=100000)
{
cout << "You entered a number that is out of range! Employee numbers are 5
digits (between 10000 and 99999). Program will now exit.";
}
else
cout << "You did not enter a number! The program will now exit.";
return 0;
}

How to make getline command work in a while loop? [duplicate]

This question already has answers here:
Why does std::getline() skip input after a formatted extraction?
(5 answers)
Closed 3 years ago.
I use getline command in a while loop. The command works fine in the first loop. But after the second loop, it just passes the getline commands and doesn't allow me to enter
I tried cin.get and cin.getline but the problem is not fixed
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int price;
void addItem(){
string product;
cout << "Please enter product's name: " << endl;
getline(cin, product);
cout << "Please enter product's price: " ;
cin >> price;
cout << "You have added " << product << " with a price of $" << price << " to your cart." << endl;
}
int main() {
char answer = 'y';
int total = 0;
while (answer == 'y'){
addItem();
total += price;
cout << "Do you want to add another product (y/n)? " ;
cin >> answer;
}
if (answer != 'y'){
cout << "Your total is $" << total << endl;
}
return 0;
}
Mixing cin >> with getline(cin,...), so you should to avoid it. I assume that you used getline to read product name which contain spaces inside. You could rewrite your code to use only getline which should give you expected behavior:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int price = 0;
void addItem(){
string product{};
string price_str{};
cout << "Please enter product's name: " << endl;
getline(cin, product);
cout << "Please enter product's price: " ;
getline(cin,price_str);
/*CHECK IF price_str is number before calling stoi*/
price = stoi(price_str);
cout << "You have added " << product << " with a price of $" << price << " to your cart." << endl;
}
int main() {
string answer = "y";
int total = 0;
while (answer == "y"){
addItem();
total += price;
cout << "Do you want to add another product (y/n)? " ;
getline(cin,answer);
}
if (answer != "y"){
cout << "Your total is $" << total << endl;
}
return 0;
}
try
while(cin>>answer && answer !='y'){
cout<<"enter again \n";
}
cout<<"ok";

How do I get the program to request for input for the string "course" before they print out the while/if statement

How do i do that without switching the sequence of asking the questions in my program? I would like to get their age, before asking about the course. However, once the age is keyed in, the program automatically proceeds to print the while/if statement.
#include<iostream>
#include<string>
using namespace std;
int main()
{
int age; //Declares the variable "age"
string name;
string course;
cout << "Hi\n"; //Prints out "Hello World"
cout << "What is your name? ";
getline(cin, name);
cout << "\nHow old are you ? "; //Ask the user their age
cin >> age; //Records the value entered by user
cout << "What course are you picking up in university ? ";
getline(cin, course);
//If number entered is smaller than 0, print the following message
while (age < 0 ) {
cout << "\nYou can't be younger than 0 years old.";
cout << "\nPlease try again";
cout << "\n\nHow old are you ? ";
cin >> age;
}
//If number entered is larger than 100, print the following message
if (age > 100) {
cout << "\nYou are such a blessed person !\n\n";
}
//If number entered is between 1 and 99, print the following message
if (age > 1 && age < 99) {
cout << "Your name is " << name << " ,and you are " << age << " years old.";
cout << "\n You are planning on taking " << course << " in university.";
}
return 0;
}
If getline() is used after cin >>, the getline() sees this newline character as leading whitespace, and it just stops reading any further.
Solution:
Call cin.ignore() before calling getline()
Or
Make a dummy call getline() to consume the trailing newline character from the cin>>
#include<iostream>
#include<string>
using namespace std;
int main()
{
int age; //Declares the variable "age"
string name;
string course;
cout << "Hi\n"; //Prints out "Hello World"
cout << "What is your name? ";
getline(cin, name);
while(true) {
cout << "\nHow old are you ? "; //Ask the user their age
cin >> age; //Records the value entered by user
if(age>=0)
break;
cout << "\nYou can't be younger than 0 years old.\nPlease try again.";
}
cout << "What course are you picking up in university ? ";
getline(cin, course);
//If number entered is larger than 100, print the following message
if (age > 100) {
cout << "\nYou are such a blessed person !\n\n";
}
//If number entered is between 1 and 99, print the following message
if (age > 1 && age < 99) {
cout << "Your name is " << name << " ,and you are " << age << " years old.";
cout << "\n You are planning on taking " << course << " in university.";
}
return 0;
}

How can I get user input to exit a loop?

I have a problem with my code, every time I loop it with the answer 'y'(Yes) it loops to infinity?
I'm trying to make a loan calculator and every time the user is done calculating with a transaction and wants to reset, and do another calculation if he enters in a value 'y', and if he enters 'n' the program will end.
Here's my code so far:
#include <iostream>
#include <string>
#include <iomanip>
#include <cmath>
using namespace std;
int main() {
char ans = 'y';
do {
string name;
int Months;
int n;
double LoanAmount, Rate, MonthlyInterest, TotalLoanAmount, MonthlyAmortization, OutstandingBalance;
cout << fixed << showpoint;
cout << "Enter Name of Borrower: ";
getline(cin, name);
cout << "Enter Loan Amount: ";
cin >> LoanAmount;
cout << "Enter Number of Months to Pay: ";
cin >> Months;
cout << "Enter Interest Rate in Percent(%): ";
cin >> Rate;
cout << setprecision(2);
MonthlyInterest = LoanAmount * Rate;
TotalLoanAmount = LoanAmount + (MonthlyInterest * Months);
cout << "Monthly Interest: " << MonthlyInterest << endl
<< "Total Loan Amount with interest: " << TotalLoanAmount << endl;
cout << setw(100)
<< "\n\tSUMMARY OF OUTSTANDING INSTALLMENT" << endl
<< "\tName of Borrower: " << name
<< "\n\nMonth\t\tMonthly Amortization\t\tOutstanding Balance"
<< "\n";
for(n = 1; n <= Months; n++) {
MonthlyAmortization = TotalLoanAmount / Months;
OutstandingBalance = TotalLoanAmount - MonthlyAmortization;
cout << n << "\t\t" << MonthlyAmortization << "\t\t\t" << n - 1 << OutstandingBalance << endl;
}
cout << "\nEnd of Transaction";
cout << "Do you want to compute another transaction?[y/n]?" << endl;
cin >> ans;
}
while(ans == 'y');
}
After your cin>>ans, add these two lines :
cin.clear();
cin.sync();
That usually fixes a lot of the infinite looping problems I get with cin.
Also, I would recommend against initializing ans as 'y' when you declare it. I don't think this is causing you problems but it's an uncessesary thing.
You seem to expect pressing y and enter to register as only 'y'. If you want to get the input of just one character have a look at std::cin.get(char)

getline() error in C++ when using for loop

I had to write a program to calculate average speed of a car during a trip and I have to prompt the user for the names of the two cities that they were traveling between. That program worked, but the next program we had to write is an addition to the last one, in which the user is prompted for how many times the program should run. I declared a new variable for the number of times the users needs the program to run. However when the program enters the loop it skips the first getline() method (asking for the origin city) and skips directly to the second getline() (method asking for the destination city). I have tried clearing the buffer and declaring the loop differently, but whatever I do the string is still read into the program as an empty string. Just wondering if I made a mistake on something or if I cannot use getline() in this instance.
Using C++ and Codeblocks IDE with the GNU Compiler (I've tried other compilers too)
Anyhow here is the code.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
//Declare Variables
string orgcity = "";
string destcity = "";
int hours = 0;
double minutes = 0.0;
int hoursmin = 0;
int minutesmin = 0;
int minutesmax = 60;
double dist = 0.0;
double totalhours = 0.0;
double avespeed = 0.0;
double num1 = 0;
cout << "How many times would you like to calculate the average speed: ";
cin >> num1;
for(num1; num1 > 0; --num1)
{
//Collect Data
cout << "Enter the city of origin: ";
getline(cin, orgcity);
cout << "Enter the destination city: ";
getline(cin, destcity);
//If Statements and Loops...Start here
do {
cout << "Enter the number of hours spent in travel: ";
cin >> hours;
if (hours < hoursmin)
cout << " Invalid number of hours - must be >= 0" << endl;
} while (hours < hoursmin);
do {
cout << "Enter the number of minutes spent in travel: ";
cin >> minutes;
if (minutes >= minutesmax){
cout <<" Invalid number of minutes - must be in range 0..59" << endl;
}
if (minutes <= minutesmin) {
cout << " Invalid number of minutes - must be in range 0..59" << endl;
}
} while (minutes >= minutesmax);
//End Here
cout << "Enter the distance (in miles) between the two cities: ";
cin >> dist;
cout << endl;
//Formula and Final Prompt
totalhours = (hours + (minutes / 60.0));
avespeed = dist / totalhours;
cout << "The average speed of the vehicle traveling" << endl;
cout << "between " << orgcity << " and " << destcity << " is " << fixed << setprecision(2) << avespeed << " miles per hour." << endl;
cout << "-------------------------------------------------------------------------------" << endl;
}
return 0;
}
When you read the number of times the loop should be run, the input operator reads the number, but leaves the newline in the buffer. This means that the first call to getline reads that single newline and nothing more.
To make sure you skip anything after that number, up to and including the newline, you can use e.g.
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');