C++ User enters a non-integer value for integer variable - c++

I am working on program where a list of options is displayed to the user and he would then enter an integer to specify which option he wants to select.Now I have pre-empted the situation where the user might enter an integer value apart from the valid ones. But if he enters any other value, say a character or a string, the program goes into an infinite loop with the list of options being printed infinitely. How can i rectify this? I mean, I should be able to give my user an error when for a predefined integer variable he enters a value that is not an integer.
Any help appreciated. Here is a sample code.
do{
printf("Select appropriate option.\n");
printf("Press 1 to do this");
printf("Press 2 to do that.\n");
printf("Press 3 to exit the program.\n");
scanf("%d",&choice);
if(choice!=1 && choice!=2 && choice!=3)
printf("You entered an invalid choice. Please enter again.\n");
switch(choice){
case 1:
//do this
break
case 2:
//do that
break;
case 3:
exit(1);
}}
while(choice!=3);
So basically when a user enters a non-integer value for choice I want the program to notify the user and ask him for another input.

It cannot be done with direct scanf into an integer variable. Such scanf will not only accept 1.23, it will also accept 1abcde and other inputs. scanf (and other conversion functions) reads as much as it can in accordance with the requested format. It stops when it finds something that does not satisfy format requirements and simply leaves it untouched.
If you want to perform this sort of analysis, you have to read the input as string and then parse and analyze that string manually.
A C-style code sketch (since you insist on C-style code, despite having tagged it as [C++]) might look as follows
char buffer[100]; /* 100 should be enough for everyone :) */
int n = scanf("%s", buffer);
if (n < 1)
/* ERROR, can't read */;
char *end;
long choice = strtol(buffer, &end, 10);
if (end == buffer || *end != '\0' || errno == ERANGE)
/* ERROR, bad format */;
/* ... */

scanf will not consume any non-digits when converting %d. It will return 0 because it didn't convert anything, and the "bad input" will still be there waiting to be consumed. You have to consume it in some way to be ready for a valid input.
(also note you're excluding 3 in your if before testing for it in your switch)

Use iostream - see http://www.cplusplus.com/reference/iostream/
Having said that if you insist on using scanf - check the return value - i.e. read http://linux.die.net/man/3/scanf

isdigit will check for any input that is a digit(number) type.
For this include header ctype.h.
Also terminate your program using exit(0) if input is incorrect.
For this include header stdlib.h.
#include<ctype.h>
#include<stdlib.h>
char c;
scanf("%c", &c);
if (isdigit(c))
{
case statement...
...
...
}
else
{
printf("Wrong input");
exit(0);
}

Related

Why does scanf_s() isn't working second time I am calling it in order to verify if user provided correct input?

I am writing an application with a menu and I am asking the user to provide an integer representing an option
from the menu
1. Option 1
2. Option 2
3. Option 3
...
This option is stored in a variable called
option
I want to avoid wrong input such as "12a", "1a2", "anyString" and I've read that this can be achieved by storing return value of scanf_s() function.
So I stored it in a variable called
ret
and now I want that every time user provides wrong input to prompt them to enter a new value.
So I wrote something like this:
int ret = scanf_s("%d", &option);
while (!ret)
{
cout << "Provide an integer, not a string! :)\n";
ret = scanf_s("%d", &option);
}
The problem is when it enters the while it is not allowing user to enter a new value and hence the value of ret never changes, making it run endlessly.
How can I achieve what I am looking for?
When scanf_s fails to convert an integer, the offending input stays in the input stream. Calling scanf_s("%d", &option) again will produce the same result until some characters are removed from the input stream. Note also that using scanf_s or scanf directly from stdin is error prone: the newline entered by the user stays in the input stream and will be read by a subsequent call to getchar() or fgets(), potentially causing unexpected behavior.
To avoid these pitfalls, it is recommended to read one line at a time with fgets() and convert it with sscanf() this way:
#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#endif
#include <stdio.h>
int main() {
char buf[80];
int option;
char cc;
for (;;) {
print_menu(); // output the menu options
if (!fgets(buf, sizeof buf, stdin)) {
/* end of file reached: break from the loop */
break;
}
/* parse exactly one integer with optional leading and trailing whitespace */
if (sscanf(buf, "%d %c", &option, &cc) != 1) {
printf("invalid input: %s", buf);
printf("enter one integer exactly\n");
continue;
}
printf("option is %d\n", option);
// handle option
}
return 0;
}

How to keep taking values from the user in C but stop when the user does not enter any value and presses enter?

int k;
vector<int>v;
while ((scanf("%d", &k)) != EOF) {
if (v.size() > 20) break;
else {
if (k > 0 && k <= 120) v.push_back(k);
}
}
**The above snippet is taken from codechef blogs **
<rant>Never tag a question both C and C++ on SO again. It is reserved for questions about interoperations or very specific language-lawyer points, and should not be used for code that could be more or less used on both languages. In that latter case choose one in your first question and if you later need it ask a new question for the other language</rant>
Your problem is that for the scanf family questions spaces and newlines are just ignored when you use a %d conversion character. And scanf returns the number of elements that could be decoded and only stops on an end of file, read error or conversion error.
If you want to be able to detect an empty input, you will have to use fgets + sscanf from the C standard library, or getline + stringstream from the C++ one.

Check scanf formating without conversions

Is there a way how to check if some specific characters were given on input using scanf without using character conversions?
int main(void)
{
if(scanf("{ ["))
printf("GOOD INPUT\n");
else
printf("BAD INPUT\n");
return 0;
}
This code always gives the bad input option (it expects scanf return value to be 1) but interestingly if I enter other than the desired characters it gives the bad input imediately but if I enter it as its specified in the scanf it blows the bad input at me AFTER I enter the whole input.
So it must be awaiting the input to be in that specified format but my question is: How can I check it, without any conversions, and make according action depending on wether the input was entered correctly or not?
You might use the %n conversion of scanf (it sets below into pos the number of characters read so far)
int pos= -1;
if (scanf("{ [%n", &pos) >=0 && pos>0)
printf("GOOD INPUT\n");
else
printf("BAD INPUT");
Beware, the return count of scanf might be implementation specific (it probably stays at 0). But pos get assigned to a positive offset of scanf did get { followed by some (zero or more) space-like characters followed by a [.
However, what you probably want is some lexical analysis and parsing, then scanf is not a good solution. You'll better read the entire line (e.g. with fgets or getline) and parse it later.
See also the man page of scanf(3)
scanf (and cousins) returns a count of the number of successful conversions. If you specify 0 conversions, then its return value will always be 0.
To use scanf for this task, I'd probably use a couple of scanset conversions:
char a[2], b[2];
if (scanf("%1[{] %1[[]", &a, &b) == 2)
printf("Matched");
Or, you could simplify this a little bit:
char a[2];
if (scanf("{ %1[[]", &a) == 1)
Either way, we've specified each scan set to match only one specified character, but it's still a conversion, so we can see whether it succeeded or failed.
Unfortunately, we still have to assign the result somewhere. scanf does support using * like this: "%*s", to tell it to read a string, but not store the result anywhere--but when you do so, that conversion doesn't get counted in the return value, so (much like before) we can't use it to determine whether we got a match or not.
If good input needs to exactly 3 characters: { space [, use "%*1[ ]" to scan a space and "%n", which saves the scan character count, to insure scanning reach the expected end.
int main(void) {
int n = -1;
scanf("{%*1[ ][%n", *n);
if (n >= 0) {
printf("GOOD INPUT\n");
} else {
printf("BAD INPUT\n");
}
return 0;
}
I'd recommend to read a line of input with fgets() first and then parse the buffer. That can leave stdin in a better known state when bad input happens.

Why does scanf appear to skip input?

I am confused about scanf's behaviour in the following program. scanf appears to input once, and then not input again, until a stream of characters is printed.
Below in a C program
#include<stdio.h>
int main()
{
int i, j=0;
do
{
++j;
scanf("%d", &i);
printf("\n\n%d %d\n\n", i, j);
}
while((i!=8) && (j<10));
printf("\nJ = %d\n", j);
return 0;
}
here, Till i am inputting any integer program works perfectly fine, but when a character is inputted it goes on printing the last inputed value of i and never stops(untill j is 10 when loop exits) for scanf to take next input.
output::
1 <-----1st input
1 1
2 <---- 2nd input
2 2
a <---- character input
2 3
2 4
2 5
2 6
2 7
2 8
2 9
2 10
J = 10
same thing is happening in c++ also.
#include<iostream>
using namespace std;
int main()
{
int i, j=0;
do
{
++j;
cin>>i;
cout<<i<<" "<<j<<"\n";
}
while((i!=8) && (j<10));
cout<<"\nj = "<<j<<"\n";
}
output of c++ program ::
1 <-----1st input
1 1
2 <-----2nd input
2 2
a <------ character input
0 3
0 4
0 5
0 6
0 7
0 8
0 9
0 10
j = 10
only change in c++ is that 0 is being printed instead of last value.
I know here integer values are expected by the program, but i want to know what happens when character is inputted in place of an integer?
what is the reason of all happening above?
When you enter a, then cin >> i fails to read it because the type of i is int to which a character cannot be read. That means, a remains in the stream forever.
Now why i prints 0 is a different story. Actually it can print anything. The content of i is not defined once the attempt to read fails. Similar thing happens with scanf as well.
The proper way to write it this:
do
{
++j;
if (!(cin>>i))
{
//handle error, maybe you want to break the loop here?
}
cout<<i<<" "<<j<<"\n";
}
while((i!=8) && (j<10));
Or simply this (if you want to exit loop if error occurs):
int i = 0, j = 0;
while((i!=8) && (j<10) && ( cin >> i) )
{
++j;
cout<<i<<" "<<j<<"\n";
}
If scanf sees a character in the input stream that doesn't match the conversion specifier, it stops the conversion and leaves the offending character in the input stream.
There are a couple of ways to deal with this. One is to read everything as text (using scanf with a %s or %[ conversion specifier or fgets) and then use atoi or strtol to do the conversion (my preferred method).
Alternately, you can check the return value of scanf; it will indicate the number of successful conversions. So, if scanf("%d", &i); equals 0, then you know there's a bad character in the input stream. You can consume it with getchar() and try again.
You can never expect your users to enter valid things. The best practice is to read the input into a string and try to convert it to integer. If the input is not an integer, you can give an error message to the user.
The problem is that when you enter an input that is not of the expected type (specified by %d for scanf, and the int type for cin>>i;, the inputstream is not advanced, which results in both operations trying to extract the same type of data from the exact same incorrect input (and failing just as well this time around too), thus you will never asked for another input.
To ensure this does not happen you will need to check the return value of both operations (read the manual for how each reports errors). If an error does happen (as when you enter a character), you will need to clear the error, consume the invalid input and try again. I find it better in C++ to read a whole line using std::gtline() instead of int or even std::string when geting input from ther user interactively, so you get into this "infinite" loop you experienced.
You are ignoring the return value. See what the manual says about scanf(3):
RETURN VALUE
These functions return the number of input items successfully matched and assigned, which can be fewer than provided for, or even zero in the event of an early matching failure.
It fails matching an integer.
You could check the return value of scanf to determine if an integer has been parsed correctly (return should =1). On failure, you have choices: either notify the user of the error and terminate, or recover by reading the next token with a scanf("%s" ...) perhaps with a warning.
For scanf, you need to check its return value to see if the conversion on the input worked. scanf will return the number of elements successfully scanned. If the conversion did not work, it will leave the input alone, and you can try to scan it differently, or just report an error. For example:
if (scanf("%d", &i) != 1) {
char buf[512];
fgets(buf, sizeof(buf), stdin);
printf("error in line %d: got %s", j, buf);
return 0;
}
In your program, since the input is left alone, your loop repeats trying to read the same input.
In C++, you check for failure using the fail method, but the input stream failure state is sticky. So it won't let you scan further without clearing the error state.
std::cin >> i;
if (std::cin.fail()) {
std::string buf;
std::cin.clear();
std::getline(cin, buf);
std::cout
<< "error in line " << j
<< ": got " << buf
<< std::endl;
return 0;
}
In your program, since you never clear the failure state, the loop repeats using cin in a failure state, so it just reports failure without doing anything.
In both cases, you might find it easier or more reliable to work with the input if you would read in the input line first, and then attempt to parse the input line. In pseudocode:
while read_a_line succeeds
parse_a_line
In C, the catch to reading a line is that if it is longer than your buffer, you will need to check for that and concatenate multiple fgets call results together to form the line. And, to parse a line, you can use sscanf, which is similar to scanf but works on strings.
if (sscanf(buf, "%d", &i) != 1) {
printf("error in line %d: got %s", j, buf);
return 0;
}
In C++, for quick low level parsing of formatted input, I also prefer sscanf. But, if you want to use the stream approach, you can convert the string buffer into a istringstream to scan the input.
std::getline(cin, buf);
if (std::cin.fail()) {
break;
}
std::istringstream buf_in(buf);
buf_in >> i;
if (buf_in.fail()) {
std::cout << "error in line " << j
<< ": got " << buf
<< std::endl;
return 0;
}

C++ Infinite Loop

I'm learning C++.
nav is an integer .
I want to ask user for typing a valid value, if he / she type an invalid value.
void main()
{
printf("Type an integer : ");
if(!scanf("%d", &nav))
{
system("cls");
printf("Invalid ! \n");
main();
}
}
But it's blinking after typing first value . It's blinking like reloading screen. I think it's infinite loop.
How can i do it in right way ? I want to ask a number from users, until it's typing a real number .
If the user types an invalid input, scanf() won't consume it, and you'll be left peeking the same offending input character forever. You need to first read whatever the user enters — I recommend using std::getline() — and then try to parse that with strtol(), sscanf() or std::istringstream. Don't use atoi() because it doesn't report failures.
int nav;
{
string line;
while (getline(cin, line))
if (istringstream(line) >> nav)
break;
}
EDIT: See the comments for a rather beautiful rendition of the above logic. I've left it out of the answer because: a) I don't want to steal someone else's idea, and b) I'm not sure I'd present a newcomer to C++ with that formulation — not in one go, at least.
P.S.: You can't call main() in C++.
Two things.
Scanf needs the 'enter' key pressed before it will process input, so the blinking could just be the cursor waiting for the next key.
Also, calling main from main is fairly non-standard. You should look into a 'while' loop.
Your program is not a good one, but nevertheless I will tell you what is happening.
In C/C++, when scanf cannot read an integer (%d) from input, it wouldn't read anything. That is, whatever prevented scanf from reading an int, will remain there. On the next scanf the same character is going to cause an error.
Let me demonstrate by an example. Imagine you are reading many integers from this input:
12 13 Shahbaz 15
Now if you call scanf with %d, you will read 12 and the input would be:
13 Shahbaz 15
Next, you call scanf with %d and you will read 13. now the input would be:
Shahbaz 15
Again, you call scanf with %d. Here, the input begins with an S (after the whitespace) which makes scanf return with a failure as it could not read an integer. The input is left untouched (save perhaps for the whitespace). That is, the input will be:
Shahbaz 15
As you can see, reading the input with %d will give you the exact same error and you are stuck in an infinite loop.
To solve this, you have many choices. This very much depends on how you want to handle the situation, but two methods would be to either read a character (with %c) or a string (with %s) right after printing printf("Invalid\n").
The first method is good for handling input like this:
12 13 q14 15
where q is a mistake that needs to be ignored. The second method is good for handling input like this:
12 13 Shahbaz 15
where the invalid data are meaningful words, but you just want to ignore them.
And the way I would write it, if I wanted to use scanf would be:
int main() // always write int main
{
int nav;
printf("Type an integer: ");
while (scanf("%d", &nav) != 1) // scanf returns number of successful %'s read
{
printf("Invalid number. Try again: ");
scanf("%*s"); // read a %s but ignore it
}
// The rest of the program, using nav
return 0;
}