简体   繁体   中英

“scanf” as a condition in while loops

I need to determine the size of an input (potentially infinite) using the "scanf" function. Now I have limitations so I cant use strings, arrays, or basically anything that is not the function.

char input;
int counter = 0;
while (scanf(" %c",&input) == 1) counter++;

The problem i'm facing is that the loop is infinite, I figured that my end condition is probably wrong. I've tried all of this.

while (scanf(" %c",&input) > 0)
while (scanf(" %c",&input) != -1)
while (scanf(" %c",&input) != EOF)

I've also tried "do-while".

Thanks for the helpers.

//Assuming that input will be space seperated and will terminate when user presses "Enter".
#include<stdio.h>
int main()
{
        char input;
        while(1)
        {
                if(scanf("%c", &input))
               {
                        /*
                        * do someething
                         */
                        if(input=='\n')
                    {
                            break;
                    }
                    else
                    {
                            printf("%c\n", input);
                    }
            }

    }
    return 0;
}

i am facing smiliar problem. When i use "while(scanf("%s", dictionary[i++]));", the loop cant end.even through i use Ctrl + D. When i usd Debug, i find loop is truly running, but the loop cant end. Thanks for your help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM