Typing a unexpected input causes loop to fail (C) - c

While testing a program(in C) to prevent any bugs, I clicked \ by accident when the program asked for an integer. The while loop then starts failing. An example:
int a;
while(1){
scanf("%d",&a);printf("%d\n",a);
a--;
if(a==0){break;}
}
Whenever I type a number, it is supposed to print the same number. But when I type a character, it will print out all numbers below the previous input and then starts printing all numbers below it till 1.
Can anyone give a clue on fixing this problem? Thanks a lot.
Edit: This program is just a sample of the bug, the actual program is much larger than this.

You won't need a while loop to print just the number you entered. This would be enough :
int a;
scanf("%d",&a);
printf("%d\n",a);
Or if you want to print from the input number till One :
int a;
while(1){
scanf("%d",&a);
printf("%d\n",a);
a--;
if(a<=0){break;}
}
Use a<=0 to compare since it would not create an infinite loop even if you entered a wrong input.

In that case, you don't need a--.
int a;
while(1){
scanf("%d",&a);
printf("%d\n",a);
if(a==0)
break;
}

Related

why does scanf() not work when followed by a loop?

When I enter a string in the code below, the program doesn't move on. It just allows me to keep typing and pressing enter with no effect. Why does this happen and how can I fix it.
#include <stdio.h>
main() {
char str[20];
int aaa = 0;
int exit;
printf("Enter anything: ");
scanf("%s", str);
while(aaa == 0) {
if(str[3] == 'a') {
aaa++; }
else {
scanf("%d", &exit);
if(exit == 3) {
aaa++; } } }
printf("%s\n", str);
}
Log:
Enter anything: 2/3/4444
Now
it
just
lets
me
keep
on
typing
Edit: I solved it and I’m a bit embarrassed at how simple it was. I know people have been trying to explain this to me but in my own words this is what was happening: as the condition to enter the while loop was being met the program would enter the while loop. However, unless the input entered for the scanf satisfied one of the conditions in the loop, the program had no way of leaving the loop and therefore, it would get stuck. Basically I was simply missing an else statement which solved this problem.
After a string whose fourth character is not an a, your program reads an integer. It will never attempt to read anything but an integer after that first read. So you must not enter anything but an integer after the first string.
If you want your program to handle a non-integer after the string, you need to add code to do that. You currently have none.

In this program to determine whether number is palindrome or not, I can't figure out what's going wrong? I think scanf isn't even taking value

I tried to detect whether a number is palindrome or not without using library functions and without array. i don't think the logic is the problem here. I introduced printf's as a checkpoint after scan and some of the loops but i think the code isn't even reading the input as it is unable to print the value of input
#include<stdio.h>
int main()
{
long a,b,x,i,j,d,y;
long g=0;
long n=0;
long c=10;
printf("Enter a number: ");
scanf("%li",&a); \\takes input
printf("%li",a); \\prints the scanned input(Checkpoint)
do{
n++;
b=a/10;
}while(b!=0); \\to determine the number of digits in input
printf("%li",n); \\(checkpoint)
x=a;
for(i=0;i<n;i++)
y=c*10;
printf("%li",y); \\(checkpoint)
for(j=0;j<n;j++) \\store the reverse value of input in g
{
d=x%c;
y=y/10;
g=g+(d*y);
x=x/10;
}
if(g==a) \\check if number is palindrome
{
printf("Palindrome");
}
else
{
printf("Not a palindrome");
}
return(0);
}
In the loop
do{
n++;
b=a/10;
}while(b!=0);
you never modify the value of a, so the result of a/10 and thus the value of b will always be the same. If a is equal to or larger than 10 then you will have an infinite loop here, as b will never be equal to zero.
Since the output before the loop isn't flushed (actually written to the terminal) then it can look like the scanf call will never return.

How I print the input character?

Hey I am beginner in programming i need help to solve this problem
I want that i input some character and i want to print it..
#include<stdio.h>
int main()
{
char a[50];
printf("Enter character...");
scanf("%s",&a[50]);
printf("You entered is %s",a[50]);
return 0;
}
From the above code I am not getting any output i also try using loop but not get any result please help me what is correct program so that if i enter any string i print on the screen?
So here's your issue.
You are defining an array of type char with a length of 50. You then read from stdin a string, and then store it at the address of the 50th element. So what will happen is you are storing the string "out of bounds" and you may get a crash, or may not.
Either way, something very bad is happening. You are writing data to an area of memory that you should not be.
So what you want to do is write that data to the address of the 0th index of the array.
You do that by using &a[0] or, for simplicity's sake: a. Both mean the same thing.
At the end of the day, what you want is this:
#include<stdio.h>
int main()
{
char a[50];
printf("Enter character...");
scanf("%s",a);
printf("You entered is %s",a);
return 0;
}
I understand you are a beginner and are learning basic concepts, but keep in mind, this code is very unsafe. Because if someone types in a length of characters longer than 50, you are back in the same boat you were before.
Quoting kaylum's comment, "It would be beneficial to go through a basic C book or tutorial before proceeding further."
Now about your issue, change these lines:
scanf("%s",&a[50]);
printf("You entered is %s",a[50]);
to
scanf("%50s", a);
printf("You entered \"%s\".\n", a);
If you just want to print what's inputted by the user then you could use buffer:
#include <stdio.h>
int main(void)
{
char c;
printf("Enter the string(~ to exit)\n");
while((c = getchar()) != '~')
putchar(c);
return 0;
}
Output:
Enter the string(~ to exit)
This is a test program // press enter
This is a test program // same output
~ // exit

Writing simple base code for a program that keeps track of my work hours and pay in C

When I compile my code it says that everything checks out but when I run it nothing happens. The program just runs until I kill the terminal.
#include<stdio.h>
int main()
{
float work;
work=0;
char ans[]="No";
while(ans[0]=='N');
{
printf("Hours worked today ");
scanf("%f", &work);
printf("Is that all? ");
scanf("%s", ans);
}
return 0;
}
You have put a ; after the while condition. Therefore your while loop is empty and will run forever.
The more readable equivalent of your program is this:
int main()
{
float work;
work=0;
char ans[]="No";
while(ans[0]=='N')
{
// empty loop thAT will run forever
}
// we never get here
printf("Hours worked today ");
scanf("%f", &work);
printf("Is that all? ");
scanf("%s", ans);
return 0;
}
In your program juste change
while(ans[0]=='N');
to
while(ans[0]=='N')
and it will work.
char ans[]="No";
...
scanf("%s", ans);
ans can hold only a string of length 2. You should make ans larger, to be able to hold any reasonable input, e.g.:
char ans[200] = "No";
Another problem is the ; after the while:
while(ans[0]=='N');
^
Remove it. It makes an empty instruction the only thing the while repeats.
Another thing: when dealing with user input, be it stdin or file input, you should check if the read was done successfully, in you case you should check the return value of scanf
Simply change
while(ans[0]=='N');
to
while(ans[0]=='N')
, because the former is identical to
while(ans[0]=='N')
{
;
}
,which will never end.

program running infinite times if entered character sometimes and sometimes not

this is a menu driven program having two functions. everything works fine if i enter numbers but when i enter character it runs infinite times sometimes :(
like when i enter integers it works fine and if i enter char it shows some junk value and then try again option is showed and i again enter char it runs infinite times
#include<stdio.h>
#include<conio.h>
#include<math.h>
void cal()
{
int x,y,z;
printf("enter two numbers\n");
scanf("%d%d",&x,&y);
z=x+y;
printf("%d\n",z);
}
void mul()
{
int x,y,z;
printf("enter two numbers\n");
scanf("%d%d",&x,&y);
z=x*y;
printf("%d\n",z);
}
void main()
{
int x,c;
clrscr();
menu :
printf("1.sum\n");
printf("2.mul\n");
printf("enter choice\n");
scanf("%d",&x);
switch(x)
{
case 1:cal();break;
case 2:mul();break;
default :printf("try again\n");
}
printf("press 5 to run another function\n");
scanf("%d",&c);
if(c==5)
{
goto menu;
}
getch();
}
You could try updating your gcc compiler. I ran the code on gcc 4.8 and the code terminated well for characters as well.
Otherwise if you really want to handle characters as well you take an input using a char pointer (string that is ) and then using atoi(str) store it in an int variable and then process it. And you can check : if the user enters characters ( using isalpha() ) then terminate the code.
Sample Code : (ran well enough)
char *s = malloc(64);
scanf("%s",s);
if(isalpha(s[0]))
return ;
else
int x = atoi(s);
int sum = x + 1; //or whatever manipulations you need to do
"when i enter character it runs infinite times sometimes ..."
All the code that tries to read an int uses the following of some sort. When non-numeric data is entered, scanf("%d", ... does not consume that IO (leaving it for the next IO operation), does not set c to any value, and then returns a 0 (which is not tested). At that point c has whatever value it had before the scanf() call. Since c was not initialized, its value could be anything - hence undefined behavior as suggested by #BLUEPIXY
int c;
...
scanf("%d",&c);
Since the non-numic data is left for the next IO and the next IO could be another scanf("%d", code is stuck in a rut - infinite loop.
To best fix, initialize variables, get the user input via fgets() and detemrine the value via sscanf() or strtol().
int c = 0;
char buf[80];
if (fget(buf, sizeof buf, stdin) == NULL) Handle_EOForIOerror();
if (sscanf(buf, "%d",&c) != 1) Handle_NonNumericInpupt();

Resources