How to use scanf after Wrong input format (the garbage value)? - c

I'm trying to get two integer inputs one by one. But when I use wrong input format like char/string/floating-point for the first input, the program ends without getting an input for the second one.
Although there are some ways to resolve this problem like using isdigit() with char input, I want to use scanf_s and "%d" for this problem.
#include <stdio.h>
int main() {
unsigned int id = 0;
printf("Enter ID\n");
scanf_s("%d", &id);
printf("%d\n", id);
unsigned int id2 = 0;
printf("Enter ID2\n");
scanf_s("%d", &id2);
printf("%d\n", id2);
return 0;
}

Like scanf, scanf_s returns the number of successfully assigned fields. So simply use:
if(scanf_s("%d", &id) != 1) {
// Handle error
}
You could do it like this:
int r;
do {
printf("Enter ID\n");
r = scanf_s("%d", &id);
} while(r!=1)

Related

How can I specify the number of “grades” in an array of integers by user input?

I’ve used the method below to achieve my goal, but to no avail.
• I want the user to specify the number of grades.
#include <stdio.h>
int main(void)
{
int user;
int grades[user], i;
for(i=0; i<grades[user]; i++) {
printf("Please enter a value: ");
scanf("%d", &grades[i]);
}
//Printing out the array
for(i=0; i<grades[user]; i++) {
printf("\nIndex Number: %d Value: %d\n", i, grades[i]);
}
return 0;
}
int main(void)
{
int user;
int grades[user], i;
At this point the value of user is uninitialized, so using it as the size of a variable length array is undefined behavior.
Rather, use scanf to read in the value of user before you use user.
scanf("%d", &user);
Remember to check the return value of scanf to ensure you actually read in an integer.

How to stop inserting values by input?

If the user has to insert a number of values and then they want to stop how can I do?
For example the user has to insert float values but if they insert a letter the loop stops. How can I create something like this:
for(;;){
scanf("%f", &n);
if(!isdigit(n))
break;
}
scanf is a poor choice for interactive user input. Especially because if the user types something that scanf does not expect, that input stays in the internal input buffer and will most likely cause trouble in the following scanfs further in the program.
I'd go for something like this:
#include <stdio.h>
int main(int argc, char * argv[])
{
float n;
char input[100];
for (;;) {
fgets(input, sizeof(input), stdin);
if (sscanf(input, "%f", &n) != 1)
break;
printf("User input = %f\n", n);
}
printf("Last line entered by user: %s", input);
}
You can use scanf return value to break the loop.
Example:
for(;;){
if(scanf("%f", &n) != 1)
break;
}
scanf will return 1 if it successfully read the float.
Give a try with this code... I think it will work fine:
#include <stdio.h>
int main() {
float n;
int check = 0;
for( ;; ) {
check = scanf("%f", &n);
if (check != 1) break;
printf("%f\n ", n);
}
return 0;
}
You can use this very simple syntax, if you are expecting query type inputs where there's no need to remember the values
float n;
while(scanf("%f",&n)){
printf(" %f",n);
}
This will break on a character input.
If you need more precautions use Jabberwocky's answer.

While loop for only accepting integer value and exiting on any other input

I'm running this program in C to convert Fahrenheit to Celsius and need to accept only integer value from the user.
Please tell me how I can modify this?
int main() {
int x;
double y;
while(x>0) {
printf("Enter the temperature in Fahrenheit:");
scanf("%d", &x);
y=((x-32)/1.8)
printf("%f\n",y);
}
}
The reason your code does not work is that sometimes scanf does not read anything, so it does not modify x.
You know that scanf read something by checking its return value. It returns the number of "scanned" items. In this case, the number must be 1.
When scanf returns 0 instead, you should read and discard the data in the buffer. You do it by supplying %*[^\n] format specifier, which means "read and discard input up to '\n' character. The complete snippet that reads an int until success looks like this:
while (scanf("%d", &x) != 1) {
printf("Please enter a valid number:");
scanf("%*[^\n]");
}
Note: It goes without saying that you should fix your syntax error with the missing semicolon ; on the line that computes y.
You can use below code.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x;
double y;
char str1[5];
int num1,i;
bool yes = true;
while(x>0)
{
printf("Enter the temperature in Fahrenheit:");
scanf("%s",str1);
for(i=0;str1[i]!='\0';i++)
if(!(str1[i]>=48&&str1[i]<=56))
{
printf("The value is invalid \n");
yes = false;
}
num1 = atoi(str1);
if(yes == true)
{
printf("This Number is %d\n",num1);
y=((num1-32)/1.8);
printf("%f\n",y);
}
}
}

In C, how to stop gets() printing a newline form previous input?

I'm having problems while using gets in C.
...
int main()
{
char test[20], m[20];
int n;
scanf("%d", &n);
while(n)
{
gets(test);
test.kolona = n;
m = decode(test); //some function
printf("%s",m.sif);
putchar('\n');
scanf("%d", &n);
}
}
When I enter a number and press enter, it automatically "prints" a newline, before you input the string. I searched a bit and found that this can be avoided if you put a gets before, like this:
...
scanf("%d", &n);
gets(test)
while(n);
{
gets(test);
...
}
But then it messes up again as the loop continues :(
Is there an elegant solution to this?
sample to fix
int main()
{
char test[20], m[20];
int n;
scanf("%d%*c", &n);//skip the newline following the numeric input
while(n)
{
scanf("%19[\^n]", test);//gets has been abolished.
//test.kolona = n;//The array does not have a member field.
//strcpy(m, decode(test));//m = decode(test); //Can not be assigned to the array in this way
printf("%s\n", m);
//putchar('\n');
scanf("%d%*c", &n);
}
}

Inputting array in C

Basically I have a C program where the user inputs a number (eg. 4). What that is defining is the number of integers that will go into an array (maximum of 10). However I want the user to be able to input them as "1 5 2 6" (for example). I.e. as a white space delimited list.
So far:
#include<stdio.h>;
int main()
{
int no, *noArray[10];
printf("Enter no. of variables for array");
scanf("%d", &no);
printf("Enter the %d values of the array", no);
//this is where I want the scanf to be generated automatically. eg:
scanf("%d %d %d %d", noArray[0], noArray[1], noArray[2], noArray[3]);
return 0;
}
Not sure how I might do this?
Thanks
scanf automatically consumes any whitespace that comes before the format specifier/percentage sign (except in the case of %c, which consumes one character at a time, including whitespace). This means that a line like:
scanf("%d", &no);
actually reads and ignores all the whitespace before the integer you want to read. So you can easily read an arbitrary number of integers separated by whitespace using a for loop:
for(int i = 0; i < no; i++) {
scanf("%d", &noArray[i]);
}
Note that noArray should be an array of ints and you need to pass the address of each element to scanf, as mentioned above. Also you shouldn't have a semicolon after your #include statement. The compiler should give you a warning if not an error for that.
#include <stdio.h>
int main(int argc,char *argv[])
{
int no,noArray[10];
int i = 0;
scanf("%d",&no);
while(no > 10)
{
printf("The no must be smaller than 10,please input again\n");
scanf("%d",&no);
}
for(i = 0;i < no;i++)
{
scanf("%d",&noArray[i]);
}
return 0;
}
You can try it like this.

Resources