Why am I having trouble with C-scanf?

Asked

Viewed 53 times

0

Hi, I’m trying to do 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 someone explain to me what’s going on?

2 answers

4

It turns out that scanf reads the string until it finds a space, so its output will be only the corresponding characters before the scanf find a space, like saida: hello.

To read a string that contains blank spaces, 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 exit should be hello world.

I hope I’ve helped.

2


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

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

See here working on ideone.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.