i have a c program in which i am accepting 2 numbers as input.
How do i validate if input entered is numbers only and not characters.
void main()
{
int a,b;
printf("Enter two numbers :");
scanf("%d%d",&a,&b);
printf("Number 1 is : %d \n Number 2 is : %d",a,b);
}
[Edit] Added Sample Code
Besides the other interesting suggestions (especially the one with scanf), you might also want to use the isdigit function:
The isdigit() function shall test
whether c is a character of class
digit in the program's current locale
note that this function examines only ONE char, not an entire bunch of them.
It is always good practice to resort to already-built functions; there are intricacies you might not be aware of even in the simplest task, and this will make you a good programmer overall.
Of course, in due time you might want to look at how that function works to get a good grasp of the underlying logic.
scanf returns the number of items that it has successfully scanned. If you asked for two integers with %d%d, and scanf returns 2, then it successfully scanned both numbers. Any number less than two indicates that scanf was unable to scan two numbers.
int main()
{
int a,b;
int result;
printf("Enter two numbers :");
result = scanf("%d%d",&a,&b);
if (result == 2)
{
printf("Number 1 is : %d \n Number 2 is : %d",a,b);
}
else if (result == 1)
{
// scanf only managed to scan something into "a", but not "b"
printf("Number 1 is : %d \n Number 2 is invalid.\n", a);
}
else if (result == 0)
{
// scanf could not scan any number at all, both "a" and "b" are invalid.
printf("scanf was not able to scan the input for numbers.");
}
}
One other value that scanf may return is EOF. It may return this if there is an error reading from the stream.
Also note that main returns int, but you have it declared with void return.
Read user line of text input as a string. This greatly simplifies error handling.
int a = 0, b = 0;
char buf[100];
for (;;) {
printf("Enter two integers :");
if (fgets(buf, sizeof buf, stdin) == NULL) {
printf("Input closed\n");
break;
}
Then test the string for 2 ints with no following junk. Use sscanf() (simple) , strtol() (more robust), etc.
int n; // %n records where scanning stopped
if (sscanf(buf, "%d%d %n", &a, &b, &n) == 2 && buf[n] == '\0') {
printf("Number 1 is : %d \n Number 2 is : %d", a, b);
break;
}
printf("<%s> is not 2 integers. Try again\n", buf);
}
More advanced code uses strtol() to validate and also detect excessively long lines of input.
Related
When I enter 2, I wish to get this output:
value: 2.4
But when I do the multiplication, I am getting this:
value: 2.400000
This is my code:
#include <stdio.h>
int main()
{
float num;
float result;
printf("Number: ");
scanf("%f", &num);
result = num * 1.2;
printf("Result: %f", result);
}
What can I do?
You can specify how many digits you want to print after the decimal point by using %.Nf where N is the number of digits after the decimal point. In your use case, %.1f: printf("Result: %.1f", result).
There are some other issues in your code. You are making use of scanf(), but you are not checking its return value. This may cause your code to break.
scanf() returns the number of arguments it successfully parsed. If, for any reason, it fails, it doesn't alter the arguments you gave it, and it leaves the input buffer intact. This means whenever you try again and read from the input buffer, it will automatically fail since
it previously failed to parse it, and
it didn't clear it, so it's always there.
This will result in an infinite loop.
To solve the issue, you need to clear the input buffer in case scanf() fails. By clearing the buffer, I mean read and discard everything up until a newline (when you previously pressed Enter) is encountered.
void getfloat(const char *message, float *f)
{
while (true) {
printf("%s: ", message);
int rc = scanf("%f", f);
if (rc == 1 || rc == EOF) break; // Break if the user entered a "valid" float number, or EOF is encountered.
scanf("%*[^\n]"); // Read an discard everything up until a newline is found.
}
}
You can use it in your main like that:
int main(void) // Note the void here when a function doesn't take any arguments
{
float num;
float result;
getfloat("Number", &num);
result = num * 1.2;
printf("Result: %.1f", result); // Print only one digit after the decimal point.
}
Sample output:
Number: x
Number: x12.45
Number: 12.75
Result: 15.3
// program to detect whether only integer has been given or not
int main() {
int a, b, s;
printf("Enter two proper number\n");
BEGIN:
s = scanf("%d %d", &a, &b); //storing the scanf return value in s
if (s != 2) {
printf("enter proper value\n");
goto BEGIN;
}
printf("The values are %d and %d ", a, b);
}
This program to detect whether only integer has been given or not goes into infinite loop when invalid data is entered instead of asking for new values
why doesn't the goto work here?
Note that when scanf gets bad input (for example you enter cat dog) that input remains in the input buffer until you take steps to clear it out. So the loop keeps repeating and rejecting the same input which is still there.
It is simpler to use fgets and sscanf and if the scan fails, you just forget the input string and get another.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int a, b;
char str[42];
do {
printf("Enter 2 numeric values\n");
if(fgets(str, sizeof str, stdin) == NULL) {
exit(1);
}
} while(sscanf(str, "%d%d", &a, &b) != 2);
printf("Numbers are %d and %d\n", a, b);
}
Program session:
Enter 2 numeric values
cat dog
Enter 2 numeric values
cat 43
Enter 2 numeric values
42 dog
Enter 2 numeric values
42 43
Numbers are 42 and 43
Note that goto is poor practice in C and should be used only where there is no other way of constructing the code — which there usually is.
There are multiple reasons scanf() can return a value different from 2:
there is pending input that cannot be converted according to the conversion specification. For example if there is an A pending in the input stream, the %d conversion fails and the A stays in the input stream. Your code just keeps trying this conversion and will never stop. You should read and discard the offending input before re-trying.
the input stream has had a read error or hit the end of file. If at least one conversion succeeded, the number of successful conversions is returned, otherwise EOF is returned. If EOF is returned, there is no point trying again since no more input will be available.
Note also that it is considered bad style to use goto for constructions that are better expressed with flow control statements such as while and for.
Here is a corrected version:
#include <stdio.h>
// program to detect whether only integer has been given or not
int main() {
int a, b, s, c;
printf("Enter two proper numbers: ");
for (;;) {
s = scanf("%d%d", &a, &b); //storing the scanf return value in s
if (s == 2) // conversions successful
break;
if (s == EOF) {
printf("unexpected end of file\n");
return 1;
}
/* discard the rest of the input line */
while ((c = getchar()) != EOF && c != '\n')
continue;
printf("Invalid input. Try again: ");
}
printf("The values are %d and %d\n", a, b);
return 0;
}
scanf returns the number of characters. As a result, s will be equal to the number of characters you have written is 2, then your loop will stop. The reason this runs infinitely many times is that the number of characters you have entered differed from 2. Print s to see what value it holds and you will get more information.
It takes in a word and a number, I can't seem to understand why the number variable won't receive the input, help please.
#include <stdio.h>
int main(void) {
char userWord[20];
int userNum;
scanf("%s", userWord);
printf("%s_", userWord);
scanf("%s", userNum);
printf("%d\n", userNum);
return 0;
}
Should be:
Input: Stop 7
Output: Stop_7
What I get:
Input: Stop 7
Output: Stop_0
Change
scanf("%s", userNum);
to
scanf("%d", &userNum);
You used format %s for reading in an integral value; it should have been %d.
Once having fixed this (i.e. by writing scanf("%d", &userNum);, note that your code will read in a string and a number even if the string and the number were not in the same line (cf., for example, cppreferene/scanf concerning format %s and treatment of white spaces). Further, you will run into undefined behaviour if a user enters a string with more than 19 characters (without any white space in between), because you then exceed your userWord-array.
To overcome both, you could read in a line with fgets, then use sscanf to parse the line. Note that you can parse the line in one command; the result of scanf is then the number of successfully read items. Further, note the %19s, which limits the input to 19 characters (+ the final string termination character '\0'):
int main() {
char line[100];
if (fgets(line,100,stdin)) {
char userWord[20];
int userNum;
if (sscanf(line, "%19s %d", userWord, &userNum) != 2) {
printf("invalid input.\n");
} else {
printf("word:'%s'; number: %d", userWord, userNum);
}
}
}
I have entries like these:
0 5 260
1 0 -598
1 5 1508
2 1 -1170
I don't know previously how many (console) inputs I'll get, so I have to read until there are no entries left.
I started with a code like this:
int a, b, c;
while(scanf("%d %d %d", &a, &b, &c)!=EOF){
// do stuff here
}
But it never stops asking for new input.
Then, I saw people in other threads suggesting this:
int a, b, c;
while(scanf("%d %d %d", &a, &b, &c)==1){
// do stuff here
}
In this case, it doesn't even enter the while.
Does anyone know what I'm doing wrong?
An approach: Continue asking for input until the input is closed (EOF) or some problem is encountered. (Invalid line of input)
The below uses fgets() to read a line.
Then, " %n" to detect where scanning stopped. If scanning does not reach %n, n will still have the value of 0. Otherwise it gets the offset in buffer where scanning stopped, hopefully it was at the null character '\0'.
char buffer[100];
while (fgets(buffer, sizeof buffer, stdin)) {
int n = 0;
sscanf(buffer, "%d%d%d %n", &a, &b, &c, &n);
if (n == 0) {
fprintf(stderr, "3 int were not entered\n");
break;
}
if (buffer[n] != 0) {
fprintf(stderr, "Extra input detected.\n");
break;
}
// do stuff here with a,b,c
}
There are many approaches to solve this issue.
while(scanf("%d %d %d", &a, &b, &c)==1)
means that "if scanf() successfully read just one value, proceed in the loop."
Therefore, if you enter something like 0 junk, the scanf() read just 1 data and will enter the loop once.
Try using
while(scanf("%d %d %d", &a, &b, &c)==3)
to have it enter the loop when scanf() successfully read three values, which is what expected.
The user has to enter a number greater than 0 in order to print some stuff.
my code for when the user enters a number less than 0 uses a while loop. It then asks the user to type in a number again.
while(x<=0){
print("Must enter a number greater than 0");
printf("Enter a number: ");
scanf("%i",&x);}
How can I create an error message formatted similarly to the one above, but for a user who enters a "x" or a word. Thanks
Since the reading is done using scanf with a numeric format, it means that if you enter something that can't be read as an integer (123) or part of an integer (123x is ok, the parsing stops soon after the 3), the scanf fails (i.e. it can't parse the input as number). Scanf returns the number of successfully parsed items. So you expect 1 in your case. You can check the return value (if it's 0, scanf wasn't able to get any number from the input) but as said before you still accept thigs like 123x (and the "residual" x will be parsed in the next scanf from stdin, if you do it).
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
int main(void){
int x;
int ok=0;
do{
char buff[32], *endp;
long long num;
ok = !ok;//start true(OK)
printf("Enter a number: ");
fgets(buff, sizeof(buff), stdin);
x=(int)(num=strtoll(buff, &endp, 0));//0: number literal of C. 10 : decimal number.
if(*endp != '\n'){
if(*endp == '\0'){
printf("Too large!\n");
fflush(stdin);
} else {
printf("Character that can't be interpreted as a number has been entered.\n");
printf("%s", buff);
printf("%*s^\n", (int)(endp - buff), "");
}
ok = !ok;
} else if(num > INT_MAX){
printf("Too large!\n");
ok = !ok;
} else if(x<=0){
printf("Must enter a number greater than 0.\n\n");
ok = !ok;
}
}while(!ok);
printf("your input number is %d.\n", x);
return 0;
}