Scanf does not work with while loop

So, I have the following code:

void main(int argc, char **argv)
{
    int loggedIn=0;
    char *currentCommand;

    while (!loggedIn)
    {
    printf("Enter your command:");
    scanf("%s",currentCommand);
    printf("\n%s\n",currentCommand);
    }
}

The problem scanf()works well for the first time, then reading starts (null), and the output will be Enter your command: (null)in an infinite loop.

I want to enter more commands and stop when I change the loggedIn value, but as soon as I enter one command, it starts to print Enter your command: (null)by default.

+4
source share
3 answers

You must allocate memory to the currentCommand pointer with malloc (and free it at the end) or specify the size at the beginning, for example

char currentCommand[256];
+3
source

currentCommand - , ( ) char 4 (32- ).

, ℅s scanf, char ( ), scanf (, currentCommand, ).

0

- i.e.,

char *p="Hello World";

/, .

scanf(). ,

0

Source: https://habr.com/ru/post/1659322/


All Articles