I'm basically expecting a number as input. The magnitude is negligible now as I know my else if loop works fine. But testing if its a number proves to be a bit trickier. I just want to call the function again and start over if the user enters in something alphanumeric or just plain words. Or pressed enter. Something that is not a number. I tried !cin since I am inputting into int numTemp, but that just results in an infinite loop that spills out "what is the bitrate" countless times. Anyone know what I'm doing wrong? I tried putting cin.clear() and cin.ignore(100, "\n") inside the first if statement but to no avail. Thanks in advance.
bool iTunes::setBitRate()
{
cout << "What is the bitrate? ";
int numTemp;
cin >> numTemp;
if (!cin)
{
cout << "WRONG" << endl;
setBitRate();
}
else if( numTemp < MIN_BITRATE || numTemp > MAX_BITRATE)
{
cout << "Bit Rate out of range" << endl;
setBitRate();
}
else
{
bitRate = numTemp;
}
}
You can just read a string from the user instead of an int, and then check it and prompt for new input if you don't like the string (e.g. if it doesn't cleanly convert to a number, which you can check with strtol).
If you want to check whether the input is a number or character, you can use isdigit, but you have to pass it a char and then when it is a digit you can convert it to a int with atoi.
When the statement cin >> numTemp fails due to non-numeric input the character causing the failure is NOT removed from the input stream. So the next time the stream extraction operator is called it will see the same non-numeric input as the last time. To avoid this you need to skip the existing input.
One way of doing this is to use getline() to read a complete line of text before trying to converting it to and integer. The folllowing code snippet illustrates this:
#include <cstdlib>
bool getint(istream& in, int & out) {
string line;
getline(in, line);
char* endptr;
out = strtol(line.c_str(), &endptr, 10);
return endptr!=line.c_str();
}
bool iTunes::setBitRate()
{
cout << "What is the bitrate? ";
int numTemp;
if ( !getint(cin, numTemp) && cin )
{
cout << "WRONG" << endl;
setBitRate();
}
else if( numTemp < MIN_BITRATE || numTemp > MAX_BITRATE)
{
cout << "Bit Rate out of range" << endl;
setBitRate();
}
else
{
bitRate = numTemp;
}
}
NOTE: You should also check the status of cin after each read to ensure that some error has not occurred.
i think this will helps
bool iTunes::setBitRate()
{
cout << "What is the bitrate? ";
int numTemp = 0;
cin >> numTemp;
if (!numTemp)
{
cout << "WRONG" << endl;
setBitRate();
}
else if( numTemp < MIN_BITRATE || numTemp > MAX_BITRATE)
{
cout << "Bit Rate out of range" << endl;
setBitRate();
}
else
{
bitRate = numTemp;
}
}
Related
I have the following bit of code that I'm using to check whether an input is a multiple of 3, 5 or Both. If the user does not enter a number I would like it to print the value stored in UserInput. At the moment it is just returning 0, any suggestions would be much appreciated!
#include <iostream>
using namespace std;
int main()
{
int UserInput;
cout << "Please enter a number:";
cin >> UserInput;
if (!cin) {
cout << UserInput;
}
else if ((UserInput%3 == 0) && (UserInput%5 == 0)) {
cout << "FizzBuzz";
}
else if (UserInput%3 == 0) {
cout << "Fizz";
}
else if (UserInput%5 == 0) {
cout << "Buzz";
}
}
If the user input cannot be read into an int, cin is placed in a fail state and nothing is read. The contents of UserInput are useless to you. You will have to take cin out of the error state with clear and read the stream into something guaranteed to be able to hold the user's input like a std::string.
if (std::cin >> UserInput) // Get input and make sure input was read check for good input
{
// do the fizbuzz thing.
}
else
{
std::cin.clear(); // remove the error flags set by reading a non-number
std::string badinput;
getline(std::cin, badinput); // read the bad input.
std::cout << "User input: " << badinput << std::endl; // write the bad input
}
I'm trying to check two separate inputs if they are integers or not. I'm able to error check one input but I'm not quite sure how to check two separate ones if I'm using the 'get' function and both inputs are from the 'cin' stream. Using c++.
My code for checking one integer is displayed below.
#include <iostream>
using namespace std;
int main() {
int input;
cout << "Enter an integer: ";
cin >> input;
char next;
int x=0;
int done = 0;
while (!done){
next = cin.get();
if (next == ' ' || next == '\n'){
cout << "The Integer that you have entered is: " << input << "\n";
done = 1;
}
else if (next == '.'){
cerr << "Error: Invalid Input. Not an Integer." << "\n";
done = 1;
}
else{
cerr << "Error: Invalid Input. Not a number." << "\n";
done = 1;
}
}
return 0;
}
Well you could use >> into an int all the way through, drop all that get() stuff and character handling, and check cin.fail(). For example (I'll leave working this into your program and repeating it in a loop as an exercise for you):
int x;
cin >> x;
if (cin.fail())
cout << "Not a valid integer." << endl;
You can handle all subsequent input in exactly the same way. There's no reason to only limit operator >> to the first input.
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 need to request a size of array, which should be posite number. Look at the function of input and cheking of it.
indexType get_array_size(){
//indexType - size_t; MAX = max of unsigned int
long long ansver;
while(true){
std:: cout << "Enter size of array{0..." << MAX/2-1 << "} ";
bool ans = std:: cin >> ansver;
if(ansver < 0 || !(ans)){
std:: cout << "Incorect size!" << std::endl;
ansver = 0;
continue;
}
break;
}
return ansver;
}
How it must work: if ansver < 0 or input incorrect(some chars for example) new request, else return obtained value. But in practice only the first request is sent, and then only cout-s "Incorect size" if input was incorrect. Please help. Ps sorry for not good english=)
When an input stream gets in a bad state, you have to:
Clear the state.
Discard the current input.
before entering new data.
while(true){
std:: cin >> ansver;
if (cin.fail()) {
std::cout << "Bad input!" << std::endl;
cin.clear(); // unset failbit
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
continue;
}
if(ansver < 0 ) {
std::cout << "Incorect size!" << std::endl;
continue;
}
break;
}
is it possible, say your trying to do calculations so the primary variable type may be int... but as a part of the program you decide to do a while loop and throw an if statement for existing purposes.
you have one cin >> and that is to take in a number to run calculations, but you also need an input incase they want to exit:
Here's some code to work with
#include <iostream>
using namespace std;
int func1(int x)
{
int sum = 0;
sum = x * x * x;
return sum;
}
int main()
{
bool repeat = true;
cout << "Enter a value to cube: " << endl;
cout << "Type leave to quit" << endl;
while (repeat)
{
int input = 0;
cin >> input;
cout << input << " cubed is: " << func1(input) << endl;
if (input = "leave" || input = "Leave")
{
repeat = false;
}
}
}
I'm aware they wont take leave cause input is set to int, but is it possible to use a conversion or something...
another thing is there a better way to break the loop or is that the most common way?
One way to do this is read a string from cin. Check its value. If it satisfies the exit condition, exit. If not, extract the integer from the string and proceed to procss the integer.
while (repeat)
{
string input;
cin >> input;
if (input == "leave" || input == "Leave")
{
repeat = false;
}
else
{
int intInput = atoi(input.c_str());
cout << input << " cubed is: " << func1(intInput) << endl;
}
}
You can read the input as a string from the input stream. Check if it is 'leave' and quit.. and If it is not try to convert it to a number and call func1.. look at atoi or boost::lexical_cast<>
also it is input == "leave" == is the equal operator. = is an assignment operator.
int main() {
cout << "Enter a value to cube: " << endl;
cout << "Type leave to quit" << endl;
while (true)
{
string input;
cin >> input;
if (input == "leave" || input == "Leave")
{
break;
}
cout << input << " cubed is: " << func1(atoi(input.c_str())) << endl;
}
}
you can use like
int input;
string s;
cint>>s; //read string from user
stringstream ss(s);
ss>>input; //try to convert to an int
if(ss==0) //not an integer
{
if(s == "leave") {//user don't want to enter further input
//exit
}
else
{
//invalid data some string other than leave and not an integer
}
}
else
{
cout<<"Input:"<<input<<endl;
//input holds an int data
}