Reputation: 605
I am writing a decryption program and I need to scan in an unknown number of strings and decode each string as it is entered. The program must end once it reaches EOF.
I am having difficulty getting the program to end. when I scan in the first char in the string in my while loop condition statement, it is doing this but when I scan in the actual string bellow the condition statement the string is missing the first char. Should I scan in the first char and then somehow put that char at the beginning of the string?
How do I properly test for EOF in my situation?
#include <stdio.h>
#include<string.h>
int main(void)
{
int i;
char code[300];
while(scanf("%c", &code[0])!=EOF)
{
scanf("%s", code);
for(i=0; i<strlen(code); i++)
{
decrypt message one char at a time
}
printf("\n");
}
return 0;
}
Upvotes: 3
Views: 25251
Reputation: 263237
Using scanf
at all is a bad idea for this particular problem.
while(scanf("%c", &code[0])!=EOF)
This scanf
call reads a single character. Just use getchar()
.
scanf("%s", code);
for(i=0; i<strlen(code); i++)
{
decrypt message one char at a time
}
The scanf
call can read arbitrarily many characters (after skipping whitespace; are you sure you want to skip whitespace?). That means that if there are too many characters to be read from stdin
, you have a buffer overflow, one that you can't avoid unless you have complete control over what appears on stdin
.
You then loop over the code
array, calling strlen()
for each character you process. Since strlen()
generally has to scan from the beginning of the array to the terminating '\0'
, this is inefficient. If you need to traverse the characters of a string, either call strlen()
once and save the value, or look for the terminating '\0'
character.
But you're just processing one character at a time, so just read one character at a time:
while ((c = getchar()) != EOF) {
/* process a character */
}
Don't worry about reading one character at a time being inefficient; buffering will take care of that.
Upvotes: 0
Reputation: 16406
while (scanf("%s", code) == 1)
{
// no need for second scanf call
...
Upvotes: 4
Reputation: 5132
while (scanf("%c", &code[0]) == 1)
{ scanf("%s", &code[1]);
...
Upvotes: 0