Quit program on 'q' character - c++

I don't know how to make a program which exit on pressing 'q' character.
I'm doing this :
#include <iostream>
#include <limits>
using namespace std;
int main()
{
double arg;
char c;
while (c!= 'q' && c != 'Q')
{
cout << "Please enter a number x (q = program quit) : " << endl;
cin >> arg;
if (cin.fail())
{
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
}
return 0;
}
Program doesn't exit on 'q' or 'Q'. It's just keep asking about "Please enter a number x (q = program quit) : ". How shall I do that ? Thanks

You have not read "c" in code.

#user1627167 thanks. It works. Code :
#include <iostream>
#include <limits>
#include <sstream>
using namespace std;
int main()
{
double arg;
string s;
while (s != "q" && s != "Q")
{
cout << "Please enter a number x (q = program quit) : " << endl;
cin >> s;
istringstream ss(s);
ss >> arg;
if (cin.fail())
{
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
}
return 0;
}

Related

alphabetic inputs run infinite loop

I wrote a function to squire number and try to cover all the input possibilities.
Overall it works fine with numeric input, but it starts a infinite loop of printing statements on screen when I enter alphabetical input.As all we know that inside computer single character like "A or a or b or B" so on is represented by integers and as i learned from my teacher that we can store single characters into a variable with integer data type. i am not talking about strings which means collection of characters . this program create problem with single character !
#include <iostream>
#include <string>
using namespace std;
void squire();
int main() {
squire();
}
void squire() {
double num = 1.0, pow = 1.0, Squire_Number = 1.0;
char ans;
reStart:
cout << "please Enter the Number: \n";
cin >> num;
cout << "please enter the nmber you want to power the number with: \n";
cin >> pow;
if (num > 0 && pow>0) {
for (int i = 1; i <= pow; i++) {
Squire_Number *= num;
}
cout << pow << " power of " << num << " is equil to : " << Squire_Number;
goto option;
}
else
{
cout << "Please enter Positve Integers. \n" ;
option:
cout<< "\nPease type 'Y' to Enter the values again OR type 'c' to Exit ! \n";
cin >> ans;
if (ans == 'y' || ans == 'Y') {
goto reStart;
} else if (ans == 'c' || ans == 'C') {
cout << "thank you for using our function. \n";
}
}
return;
}
Better try to read the input in an std::string, then parse the string to check if you only have numeric characters and then use std::atoi to convert the string in integer. One last recomendation, avoid to use goto instructions, this practice make a code difficult to read.
#include <iostream>
#include <string>
#include <cstdlib>
bool OnlyNumeric(const std::string& numStr)
{
size_t len= numStr.length();
int i;
for (i=0;i<len && numStr[i] <='9' && numStr[i] >='0';i++) ;
return i == len;
}
int main()
{
std::string inputStr;
int num;
do{
std::cout << "Input number:\n";
std::cin >> inputStr;
}
while (!(OnlyNumeric(inputStr) && (num=std::atoi(inputStr.c_str())) ));
std::cout << "Your number is : " << num;
return 0;
}

Getting rid of white spaces (C++)

My code allows the user to input numbers, it sorts them, and outputs them in order.
Example input: 25,1,3-6
Example output: 1,3,4,5,6,25
However when the user inputs something like 2 5,1,3-6, and if there is a space in a case like 3 - 6, the program doesn't work.
I used cin>>ws; to try to get rid of whitespace, however it is not working.
Here is the part of the code related to this issue (there are a few other functions I did not include, unless they seem to the source of the issue):
#include <iostream>
#include <string>
#include <cctype>
#include <vector>
using namespace std;
void get_nums(vector<int>& num_vec);
int main ()
{
int num1;
int num2;
cout << "\n Please, enter your HW: ";
vector<int> num_vec;
cin>>ws;
cout.flush();
do
{
cin>>ws;
cin>>num1;
num_vec.push_back(num1);
if(cin.peek() == ',')
{
cin.ignore();
}
else if(cin.peek() == '-')
{
cin.ignore();
cin>>num2;
for(++num1; num1<=num2; num1++)
{
num_vec.push_back(num1);
}
if(cin.peek() == ',')
{
cin.ignore();
}
}
}
while (cin.peek() != '\n');
cout<< "\n Do Problems: ";
for(int z=0; z<num_vec.size(); z++)
{
if(z+1==num_vec.size())
{
cout<<num_vec[z];
}
else if(z+2==num_vec.size())
{
cout<<num_vec[z]<<",and ";
}
else
{
cout<<num_vec[z]<<", ";
}
}
return 0;
}
I would use std::getline() to read the user's entire input in one go, and then use std::istringstream to parse it, eg:
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <algorithm>
void get_nums(std::vector<int> &num_vec)
{
std::string line, tokens;
std::getline(std::cin, line);
std::istringstream input(line);
while (std::getline(input, tokens, ','))
{
std::istringstream values(tokens);
int num;
if (!(values >> num))
continue;
values >> std::ws;
char ch = values.peek();
if (ch == '-')
{
values.ignore();
int num2;
if (!(values >> num2))
continue;
while (num <= num2)
num_vec.push_back(num++);
}
else if (ch == std::char_traits<char>::eof())
num_vec.push_back(num);
}
}
int main()
{
std::vector<int> num_vec;
std::cout << "\n Please, enter your HW: " << std::flush;
get_nums(num_vec);
if (!num_vec.empty())
{
std::sort(num_vec.begin(), num_vec.end());
std::cout << "\n Do Problems: ";
std::cout << num_vec[0];
for(int z = 1; z < num_vec.size(); ++z)
{
std::cout << ", ";
if ((z+1) == num_vec.size())
std::cout << "and ";
std::cout << num_vec[z];
}
}
else
std::cout << "\n No Input! ";
return 0;
}
Input: 25,1,3-6
Output: 1,3,4,5,6,25
Input: 25,1,3 - 6
Output: 1,3,4,5,6,25
Input: 2 5, 1 , 3- 6
Output: 1,3,4,5,6 1
1: 2 5 is not valid input in this code. If you want it to be, you will have to add some extra code to handle space-delimited numbers in addition to comma-delimited numbers.

Simple user input validation not working

I have a simple function that accepts either 1 or 2 and reprompts for input if neither of those two numbers are entered. Right now, if I enter any number, it stays stuck on asking for valid input. I know it's something easy, but I'm not seeing it now. What am I missing?
#include <iostream>
#include <string>
using namespace std;
int userChoice();
int main()
{
userChoice();
return 0;
}
int userChoice()
{
int input = 0;
cout << "Enter 1 or 2: ";
cin >> input;
while (input != 1 || input != 2 || cin.fail())
{
if (cin.fail())
{
cin.clear();
cin.ignore(1000, '\n');
}
cout << "Enter only 1 or 2: ";
cin >> input;
}
return input;
}
The conditional in while is not formed correctly. It will be always true.
You need to use something like:
while ( !cin || (input != 1 && input != 2) )
Suggestion for change of strategy
I think it will be better to use a recursive function:
int userChoice()
{
int input = 0;
cout << "Enter 1 or 2: ";
cin >> input;
// If we get a valid input, return.
if ( cin && (input == 1 || input == 2))
{
return input;
}
// If there is any error in reading, clear the stream.
if ( !cin )
{
cin.clear();
cin.ignore(1000, '\n');
}
// Call function again.
return userChoice();
}
Change the while condition to
while( (input != 1 && input !=2) || cin.fail())
use && not ||
#include <iostream>
#include <string>
using namespace std;
int userChoice();
int main()
{
userChoice();
return 0;
}
int userChoice()
{
int input = 0;
cout << "Enter 1 or 2: ";
cin >> input;
while ((input != 1) && (input != 2))
{
if (cin.fail())
{
cin.clear();
cin.ignore(1000, '\n');
}
cout << "Enter only 1 or 2: ";
cin >> input;
}
return input;
}

How to clear the previous input in c++?

'cause my program joins the previous input to my current input. I want to clear the previous input.
This is the code:
#include <cstdlib>
#include <iostream>
#include <math.h>
#include <conio.h>
using namespace std;
int main()
{
int ini=1,an=1,ans=1, f=1;
int bb=2;
int hypin;
string a="a.) Hyperfactorial";
string b="b.) Superfactorial";
string c="c.) Primorials";
string d="Exit";
string e="a. Yes";
string ff="b. No";
string letter;
string ysno;
start:
cout<<"\n"<<"Factorial"<<"\n"<<a<<"\n"<<b<<"\n"<<c<<endl;
cout<<"\n"<<"Enter letter:"<<endl;
cin>>letter;
if (letter=="a"){
cout<<"\n"<<"Enter number (maximum input:7) : "<<endl;
cin>>hypin;
if(hypin>=8){
cout<<"\n"<<"Invalid input!"<<endl;
}else{
while (hypin>1){
ini=ini*(pow(hypin,hypin));
hypin--;
}
cout<<"\n"<<"The hyperfactorial is: "<<ini<<endl;}
cout<<"\n"<<"Do you want to test another factorial?"<<"\n"<<e<<"\n"<<ff<<endl;
cout<<"\n"<<"Answer: ";
cin>>ysno;
if(ysno=="a"){
goto start;
}
if(ysno=="b"){
cout<<"\n"<<"Press any key to exit"<<"\n"<<endl;
getch();
return 0;
}
}
system("PAUSE");
return EXIT_SUCCESS;
}
Try clearing the cin buffer using
std::cin.ignore(INT_MAX);
Edit: You have to #include <limits.h> to use INT_MAX
You don't need to clear any thing. infact you have some little bug in your code that not set the answer every time.
I try to write a simple code for you:
bool validInput = false ,continueFlag = true;
string opr, ysno;
int a , b, ans = 0;
while(continueFlag)
{
cout << "Choose operation: a. Multiply b. Add \n Enter letter: " << endl;
cin >> opr;
if (opr != "a" && opr != "b")
{
cout << "Invalid input!"<<endl;
continue; // it returns to "while(continueFlag)" line
}
cout << "Enter First Number: ";
cin >> a;
cout << "Enter Second Number: ";
cin >> b;
if (opr == "a")
{
ans = a * b;
}
else
{
ans = a + b;
}
cout << "Answer is : "<< ans << endl;
do
{
cout << "Do you want to test another factorial? a. Yes b. No" << endl;
cin >> ysno;
if (opr != "a" && opr != "b")
{
cout << "Invalid input!"<<endl;
continue; // it returns to "do" line
}
validInput = true;
if (ysno == "b")
{
continueFlag = false;
}
}while(!validInput);
}
try this might be helpful
cout << "\033[2J\033[1;1H";
I used this code and compiled with g++ its working and linux platfrom(ubuntu)
#include <cstdlib>
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int ini=1,an=1,ans=1, f=1;
int bb=2;
int hypin;
string a="a.) Hyperfactorial";
string b="b.) Superfactorial";
string c="c.) Primorials";
string d="Exit";
string e="a. Yes";
string ff="b. No";
string letter;
string ysno;
start:
cout<<"\n"<<"Factorial"<<"\n"<<a<<"\n"<<b<<"\n"<<c<<endl;
cout<<"\n"<<"Enter letter:"<<endl;
cin>>letter;
if (letter=="a"){
cout<<"\n"<<"Enter number (maximum input:7) : "<<endl;
cin>>hypin;
cout << "\033[2J\033[1;1H";
if(hypin>=8){
cout<<"\n"<<"Invalid input!"<<endl;
}else{
while (hypin>1){
ini=ini*(pow(hypin,hypin));
hypin--;
}
cout<<"\n"<<"The hyperfactorial is: "<<ini<<endl;}
cout<<"\n"<<"Do you want to test another factorial?"<<"\n"<<e<<"\n"<<ff<<endl;
cout<<"\n"<<"Answer: ";
cin>>ysno;
if(ysno=="a"){
goto start;
}
if(ysno=="b"){
cout<<"\n"<<"Press any key to exit"<<"\n"<<endl;
return 0;
} }
system("PAUSE");
return EXIT_SUCCESS;
}

stuck on with input validation in c++ either string or integer

I am trying to practice my input validation in C++. How can i let the program validate the user input when a user is asked to enter a number or string?
Here is a sample of my code.
public:
void CreateProduct() {
inputProduct:
system("cls");
cout << "\n\n\n\n\n\n\n\t\t\t\tPLEASE PROVIDE ACCURATE INFORMATION";
cout << "\n\n\t\tPRODUCT NUMBER: ";
cin >> ProductNumber;
if (!cin) {
cout << "\nPlease provide an integer";
cin.clear();
cin.end;
goto inputProduct;
//when enter a string i should enter this if statement and exit
// to be asked for another entry but am getting stuck in a loop.
}
system("cls");
cout << "\n\n\n\n\n\n\n\t\t\t\tPRODUCT NAME: ";
cin >> ProductName;
system("cls");
cout << "\n\n\n\n\n\n\n\t\t\t\tPRICE: ";
cin >> Price;
system("cls");
}
Please help me understand this input validation.
You can check whether input is number or not by checking ascii value of each character in input .
#include <iostream>
#include <cstring>
#include <string>
int main(void)
{
std::string str;
std::cin>>str;
bool isNumeric = true;
for(size_t i=0;i<str.length();++i)
{
if(str[i]< '0' || str[i] > '9')
{
isNumeric = false;
break;
}
}
if(!isNumeric)
{
std::cout<<"Input is not an integer";
exit(1);
}
return 0;
}