Why am I having problems with 'scanf' in C?

0

Hello, I'm trying to make a very basic cmd, but I'm having problems ...

My code:

#include <stdio.h>

int main()
{
    char arg[300];

    scanf("print '%s'", arg);
    printf("%s", arg);

    fgetc(stdin);
    fgetc(stdin);
    return 0;
}

So I went to test:

entrada: print 'hello world'
saída: hello //não coloca o que eu queria

But what I wanted was:

entrada: print 'hello world'
saída: hello world

Can anyone explain what's going on?

    
asked by anonymous 31.08.2018 / 23:51

2 answers

2

Because %s reads a word. This means that the whitespace between hello and world is one of the things that makes it stop reading.

Use %[^']s instead. This [^'] means something like " read while not finding a ' character."

See here working on ideone.

    
01.09.2018 / 00:15
4

It happens that scanf performs the string reading until it finds a space, so its output will be only the corresponding characters before scanf find a space, such as saida: hello .

To read a string that contains blanks, I recommend that you use the command fgets(var, size_var, stdin) in C.

int main(void) {
    char arg[300];

    printf("print "); 
    fgets(arg, 300, stdin); //realiza a leitura de uma string com espaços
    printf("%s", arg);

    fgetc(stdin);
    fgetc(stdin);

    return 0;
}

Now your output should be hello world .

I hope I have helped.

    
01.09.2018 / 00:22