Not sure why while loop works different when using scanf
NickName:Rudalf Ask DateTime:2019-06-13T21:29:17

Not sure why while loop works different when using scanf

I'm new in the journey of learning C and to my knowledge, I knew that while loop would run forever if someone gives condition such as while (1 == 1) it would become a forever loop.

But While reading from a book I noticed a code such as

#include<stdio.h>

int main() {

    char a;
    int started = 0;
    puts("Scanning\n");
    while (scanf("%s[^\n]",&a) == 1)
    {
        if (a >= 65 && a <= 90)
        {
            printf("Char is capital\n");
        }
        else
        {
            printf("Not cap.\n");
        }

    }
    puts("Done\n");
    return 0;


}

Command line => char.exe < file.txt

It takes input from stdin but scanf returns the number of argument i.e 1 so the condition should become while (1 == 1)

But why this is not a forever loop and exists after reading the file?

Thanks

Copyright Notice:Content Author:「Rudalf」,Reproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/56581647/not-sure-why-while-loop-works-different-when-using-scanf

Answers
bruno 2019-06-13T13:40:23

In\n\nchar a;\n...\nwhile (scanf(\"%s[^\\n]\",&a) == 1)\n\n\nyour format is invalid because dedicated to a string while you want to read only a char, so you will write out of the char at least for the ending null char producing an undefined behavior\n\ndo\n\nchar a;\n...\nwhile (scanf(\" %c\",&a) == 1)\n\n\nand notice the space in the format, remove it if you want to manage all the characters\n\nIn\n\n\n if (a >= 65 && a <= 90)\n\n\n\nit is wrong to use ASCII code, this is not readable and not compatible with non ASCII\n\nyou can do\n\nif (a >= 'A' && a <= 'Z')\n\n\nor better use isupper (<ctype.h>) because it is not guaranty than the uppercase letters are consecutive\n\nYour printf can be replaced by puts removing the \\n in the string, or a fputs, is is useless to have printf to print a simple string (without % and arg)\n\n\n But why this is not a forever loop and exists after reading the file?\n\n\nscanf does not return 1 on EOF, so the loop stops on EOF, about scanf family :\n\n\n These functions return the number of input items successfully matched and assigned, which can be fewer than provided for, or even zero in the event of an early matching failure.\n \n The value EOF is returned if the end of input is reached before either the first successful conversion or a matching failure occurs. EOF is also returned if a read error occurs, in which case the error indicator for the stream (see ferror(3)) is set, and errno is set indicate the error.\n",


John Bollinger 2019-06-13T13:40:36

\n But why this is not a forever loop and exists after reading the file?\n\n\nIt will loop indefinitely only if scanf returns 1 every time it is called. The loop terminates the first time that function returns a different result.*\n\nscanf's return value conveys the number of input fields successfully scanned and assigned, and under some circumstances also conveys information about I/O errors. In particular, scanf will return the value of macro EOF if it reaches the end of the input before matching any fields. EOF is unequal to 1.\n\n\n\n*Provided that the program's behavior is well defined. Your program's is not, for reasons described in comments and another answer.",


akshay kishore 2019-06-13T13:42:29

The function scanf returns the following value:\n\n\n>0 The number of items converted and assigned successfully.\n0 — No item was assigned.\n<0 — Read error encountered or end-of-file (EOF) reached before any\nassignment was made.\n",


Amankumar Singh 2019-06-13T13:48:28

When you enter a letter the condition (1==1) becomes true and the body of while loop is iterated.\n\nAfter iteration of while loop it goes for next letter. scanf waits till you enter next character.\n\nAgain condition (1==1) is satisfied. \n\nThis loop is an indefinite loop and you could go on entering letters and you would never reach the puts statement.",


More about “Not sure why while loop works different when using scanf” related questions

Not sure why while loop works different when using scanf

I'm new in the journey of learning C and to my knowledge, I knew that while loop would run forever if someone gives condition such as while (1 == 1) it would become a forever loop. But While reading

Show Detail

Using scanf in a while loop

Probably an extremely simple answer to this extremely simple question: I'm reading "C Primer Plus" by Pratta and he keeps using the example while (scanf("%d", &amp;num) == 1)... Is the == 1 really

Show Detail

Usage of scanf in while loop

I have to read a series of input from a file using scanf. But there are different outcomes in 2 situations. Code1- Reading an integer and a char array. char plaintext[20]; int started = 0; int x; ...

Show Detail

Why is scanf stuck inside a while loop?

I used a scanf() inside a while loop. while(1) { int input = 0; scanf("%d\n", &amp;input); printf("%d\n", input); } When I run this program, and I enter a number, the printf() is no

Show Detail

User input with scanf using while loop

I'm having a problem with multiple characters while using a while loop. I'm writing a code that would direct the user to a new function based on the input of either &quot;y&quot; or &quot;n&quot;. ...

Show Detail

scanf in a while loop reads on first iteration only

NOTE: Please notice this is not a duplicate of Why is scanf() causing infinite loop in this code? , I've already seen that question but the issue there is that he checks for ==0 instead of !=EOF. A...

Show Detail

Why is scanf and printf value different?

In my program: int row,col,srow,scol,erow,ecol; while(scanf(&quot;%d %d %d %d %d %d&quot;,&amp;row,&amp;col,&amp;srow,&amp;scol,&amp;erow,&amp;ecol)!=EOF){ int m[row][col]; ... } Inside

Show Detail

Why does this scanf in a while loop work?

I can't understand why this does exactly what I want. The part where I used two scanf's in the loop confuses me. I compiled it using devcpp. #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; int...

Show Detail

scanf error on while loop (and for loop), scanning forever

I'm new to C programming and writing code to determine prime factorization for M test cases. The function itself works if I'm only scanning once at a time, but fails miserably when I tried to do it M

Show Detail

calling scanf inside do while loop is breaking the loop

I have a do while loop. When I run it without scanf(), it runs properly. But if I enter a scanf() it breaks the loop! Why??? The code: With scanf() void main(){ int num = prng() % 100, guessed,

Show Detail