Reputation: 1
I have to write a program in C for class that reads in one character at a time and we have to use scanf. I got it to work with input from only the keyboard however, my teacher will be testing the code with file redirection as well.
int end; //return value of scanf
int length1; //length of string exp1
char temp, //temp char for input
char exp1[81]; //string
printf ("Please enter in a regular expression:\n");
end = scanf ("%c", &temp);
while (temp != '\n' || end == 1) { //check if end of input
length1 = check(temp, length1, exp1); //returns length of exp1
end = scanf ("%c", &temp); //scan next char for loop
}
I've been at this one tiny problem for hours trying to figure it out so any pointers are helpful. Thanks!
EDIT: I've tried using the kbhit() function in an if statement to check if they typed in the input or if the input is from a file. However, I don't have conio.h, is there any alternative while still using scanf?
Upvotes: 0
Views: 33178
Reputation:
Your narrower-scope question has already been answered, but let me give you a piece of good advice. If you are not forced to use scanf()
in class (i. e. you are writing real, production code), then
Just get rid of scanf()
. It's evil. It does not do what you think it does.
If you want to get one character at a time, then use the function that gets one character at a time. And that is fgetc(stdin)
.
int c;
while ((c = fgetc(stdin)) != EOF) {
/* process `c' */
}
Upvotes: 5
Reputation: 22823
You need to compare scanf output with EOF
while(scanf("%c", &temp) != EOF)
{
}
You could convert this to something like:
do{
length1 = check(temp, length1, exp1); //returns length of exp1
end = scanf ("%c", &temp); //scan next char for loop
}while (temp != '\n' && end != EOF) ;
Upvotes: 1
Reputation: 122383
scanf
returns EOF
if an input failure occurs before the first conversion (if any) has completed. So you may check on that. But you only read one character each time, that doesn't seem necessary since you already check if the return value if 1
.
I think the error is in the logic in your while
condition, it should be:
while (temp != '\n' && end == 1)
// ^^
Upvotes: 1