Reputation: 6413
#include <stdio.h>
int main()
{
char _char = 32;
int x, p, i, d;
scanf("%d ", &x);
while(_char == 32)
_char = getchar();
x = x%26;
printf("The encrypted string is: ");
while((_char >= 'a' && _char <= 'z') || (_char >= 'A' && _char <= 'Z'))
{
if(_char >= 'a' && _char <= 'z')
_char = 'a' + (_char + x - 'a')%26;
else
_char = 'A' + (_char + x - 'A')%26;
d = 'a' - 'A';
p = (_char >= 'a') ? _char - d : _char + d;
printf("%c", p);
scanf("%c", &_char);
}
return 0;
}
Code description : the program receives a number 'x' followed by spaces and then a sequence of letters , then it will print these letters (modified) until the first number or when there is no more letters to receive . It works fine when I run it in Code blocks but when I use CMD to insert the inputs as a file , this gives me an infinite loop if I insert :
1 FffF
when I add 0 or any number it works fine :
1 FffF0
the infinite loop is sth like :
The encrypted string is:
BBBcccDDDeeefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz....
how can I slove this !?
Upvotes: 0
Views: 759
Reputation: 47770
You don't check the return value of scanf
, so you don't detect that the input has ended. Scanf returns number of matched items, which is 1 in your case when successful. When end-of-file is reached before the first item, it returns -1.
So you should break
of the loop when scanf
doesn't return 1.
Upvotes: 1
Reputation: 183968
If there is no more input to scan,
scanf("%c", &_char);
doesn't modify _char
. You have to check the return value of the scan,
if (scanf("%c",&_char) < 1) break;
to exit the loop then.
Upvotes: 3