My program can either accept a number of any length or empty input. However, if the input is empty (space or newline), the program continues to wait for an input. I also tried fgets
but if space/newline is pressed, it still waits for more input that is not a space/newline before closing.
Simpified code:
#include <stdio.h>
main()
{
int num;
scanf("%i",&num);
printf("%i",num);
}
Input:
363792
Output:
363792
Desired:
Input:
Output:
I'm new to C and am having a very hard time accomplishing this.
What tried using fgets:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
main()
{
int n;
char s[20];
fgets(s,20,stdin);
n = atoi(s);
printf("%i",n);
}
Edit: Turns out I was not compiling the code right. So every time I tried to make changes, it just looked at the original code using scanf.
In C language strings are terminated with a null character \0 , so we can check if a given string is empty or not by verifying if a string contains the first character is \0 . Note: C language doesn't have any built-in function to check if a string is empty, like we have a empty() function in C++.
Strings are actually one-dimensional array of characters terminated by a null character '\0'. Thus a null-terminated string contains the characters that comprise the string followed by a null. The following declaration and initialization create a string consisting of the word "Hello".
Answer: Use the === Operator You can use the strict equality operator ( === ) to check whether a string is empty or not.
The empty string is a legitimate string, upon which most string operations should work. Some languages treat some or all of the following in similar ways: empty strings, null references, the integer 0, the floating point number 0, the Boolean value false, the ASCII character NUL, or other such values.
I also tried fgets but if space/newline is pressed, it still waits for more input that is not a space/newline before closing.
Firstly fgets
will work in this case. If you had shown us what exactly you tried to do using fgets()
then answer to this question would have much narrow or very specific.
I tried to do the same using fgets()
and below is the code snippet.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
char string[100];
printf("Enter a number: ");
fgets (string, 100, stdin);
/* Here remove the trailing new line char; not required unless you are trying to print the string */
string[strlen(string) - 1] = '\0';
printf("Num is %d\n", atoi(string));
return 0;
}
If there is no input or just enter or space and enter, then number printed will be zero and fgets() will not wait until you enter a valid number.
Also check this on why you shouldn't use gets. Do not use gets()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With