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

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";

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 can I stop cin from skippping a line? [duplicate]

This question already has answers here:
Why does std::getline() skip input after a formatted extraction?
(5 answers)
cin and getline skipping input [duplicate]
(4 answers)
Closed last year.
I was trying to make a program where the user is asked to give an input and it gives output with answered questions. Everything looks alright except that cin skipped my last question about school.
This is the original code:
//this program fills my data in profile
#include <iostream>
#include <string>
using namespace std;
int main () {
int age, exp_years;
char desired_grade;
string school_name, name;
const int year_grad = 4;
bool is_student;
cout << "You will need to enter your data for portfolio card" << endl;
cout << "Enter your last name" << endl;
cin >> name;
cout << "Enter your age" << endl;
cin >> age;
cout << "Enter your years of work experience" << "\n";
cin >> exp_years;
cout << "Is it true or false that you are a student (put 'true' or 'false')" << endl;
cin >> is_student;
cout << "Great! What school are you in (if you are not a student put desirable school)?" << endl;
cin >> school_name;
/* trying to make a function below */
cout << "Awesome, here is your info" << endl << "Your last name is "<< name << endl <<"You are "<<age << " years old." << endl << exp_years << " years of work experience" << endl;
if ( is_student == 1)
{
cout << school_name << " is lucky to have you!\n";
return 0;
} else {
cout << "Btw I am sure that " << school_name << " would be happy to have you as their student anytime\n";
return 0;
}
return 0;
}
I read some article and they said that getline() can help, so I tried to substitute with:
cout << "Is it true or false that you are a student (put 'true' or 'false')" << endl;
getline(cin, is_student);
cout << "Great! What school are you in (if you are not a student put desirable school)?" << endl;
getline(cin, school_name);
Hovewer, it gives me an error:
error: no matching function for call to 'getline'
What am I missing?
It seems the problem is related to entering a boolean value.
Here is shown how to enter boolean values
#include <iostream>
#include <iomanip>
int main()
{
bool is_student;
std::cin >> is_student; // accepts 1 as true or 0 as false
std::cout << is_student << '\n';
std::cin >> std::boolalpha >> is_student; // accepts strings false or true
std::cout << is_student << '\n';
}

Skips the first prompt instead [duplicate]

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.

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)

reading and printing inputs and C-string in C++

I have a simple program to read and echoed the user's input and calculate the total amount. I'm having trouble with arrays. I want to know how to use an array to read and print each product name and the cost and the find grand total upon checkout. Should I also use functions?
#include <iostream>
#include <cstring>
#include <iomanip>
using namespace std;
const int MAX_CHAR = 100;
void pause();
int main()
{
char productName[MAX_CHAR];
double price;
char reply;
double total = 0;
cout << fixed << showpoint << setprecision(2);
cout << "Welcome to your shopping calculator!" << endl;
do {
cout << "Enter the product name: ";
cin.get(productName, MAX_CHAR, '\n');
cin.ignore(100, '\n');
cout << "Enter the amount: $";
cin >> price;
while (!cin) {
cin.clear();
cin.ignore(100, '\n');
cout << "Invalid amount. Please enter the amount: $";
cin >> price;
}
cin.ignore(100, '\n');
cout << "The product name is" << " " << productName << " "
<< " and it costs" << " " << "$" << price << endl;
total += price;
cout << "The total amount is " << " " << total << endl; //program needs to keep a running total
cout << "Would you like to continue shopping? (y/n): ";
cin >> reply;
cin.ignore(100, '\n');
} while ( reply == 'Y' || reply == 'y'); //the program will continue until the user wants to checkout
pause();
return 0;
}
void pause()
{
char ch;
cout << "Press q followed by Enter key to continue....." << endl;
cin >> ch;
}
Thanks for the help!
You need to map the product name to the cost using std::map so that you can print the respective pairs afterwards. As for the grand total, that's stored in the variable total so printing it is trivial.
To do this, you will need to include the <map> header, as the Standard Library class std::map is defined there. Moreover, I've also included some changes to your code that should be considered. In particular, using std::string and using std::numeric_limits<...>::max() to return the constant.
#include <iostream>
#include <string>
#include <map>
int main()
{
std::string productName;
double price;
char reply;
double total = 0;
std::map<std::string, double> productToPrice;
std::cout << std::fixed << std::showpoint << std::setprecision(2);
std::cout << "Welcome to your shopping calculator!" << std::endl;
while ((std::cin >> reply) && (reply == 'y' || reply == 'Y'))
{
cout << "Enter the product name: ";
std::cin >> productName;
cout << "Enter the amount: $";
while (!(cin >> price))
{
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
cout << "Invalid amount. Please enter the amount: $";
}
total += price;
productToPrice.insert(std::make_pair(productName, price));
cout << "Would you like to continue shopping? (y/n): ";
}
...
}
Note the changes I made. Please use them.
To print you simply do:
typedef std::map<std::string, double>::const_iterator iter_type;
for (iter_type beg(productToPrice.begin()),
end(productToPrice.end()); beg != end; ++beg)
{
std::cout << beg.first << " -- " << beg.second << std::endl;
}
std::cout << "\nThe total price is: " << total;
You are definitely on the right track. I think you are mixing I/O conventions in C and C++ which is causing a lot of your issues. It would be very helpful if you could elaborate on what exactly your issues are.
Carpetfizz is correct in that since you don't know the number of items at compile time, you will need to use a dynamic array with std::vector. You can learn about vectors here.
In addition, C++ has a very useful string data type that you can include with #include <string>. Using this, as well as a junk string such as string junk;, you can avoid using cin.ignore(...) and get cleaner I/O by using getline(cin, junk).
I strongly recommend doing this because creating a vector of C-strings or C-style strings is a pain, because C-style strings are actually arrays of characters, so you'd have to use std::vector<std::vector<char> > products.