print of char returns random character

0

Compile the code below without error. When I enter the word (or phrase), printf returns a random character like 0 a etc. The program should read a word (or phrase) and printf show the word (or phrase) that was written by the user.

Use gcc as a compiler. I am compiling for the terminal at the moment. The distro that I'm using is Manjaro 17.0.5 (I do not know if it interferes with anything).

#include <stdio.h>

int main (void){

  char example[20];

  scanf("%*c", &example);
  printf("example: %c\n", example);

  return 0;
}
    
asked by anonymous 03.11.2017 / 02:36

3 answers

2

Try like this:

int main(int argc, char** argv) {
    char example[20];

    scanf("%[^\n]", &example);
    printf("example: %s", example);
    return 0;
}
    
03.11.2017 / 02:53
3

You are trying to read a word / phrase:

  

The program should read a word (or phrase) and printf show the   word (or phrase)

But then use% w_that indicates caratere (only one):

scanf("%*c", &example);
printf("example: %c\n", example);

There are several solutions, and some have already been addressed in other resposites such as %c with scanf .

If you want a robust solution, use %s , which allows you to specify the maximum number of jobs to read and have the guarantee that it will never read more characters than the indicated limit.

Example with fgets :

#include <stdio.h>

int main (void){

  char example[20];

  fgets(example, 20, stdin);
  printf("example: %s\n", example); //%s para string

  return 0;
}

Example on ideone

The three parameters of fgets are:

  • Location where read content is placed
  • Maximum length of characters to read
  • Where reading is done, fgets indicates input stream that will match the keyboard
  • 03.11.2017 / 03:08
    1

    Its distribution does not interfere, I also use linux and the same problem. Your code did not test on a Windows Operating System, so I do not know if that's what you've developed that will work. But regarding String, your code would look like this:

    #include <stdio.h>
    
    int main (void){
    
      char example[20];
    
      scanf("%s", &example);
      printf("example: %s\n", example);
    
      return 0;
    }
    

    You only have to be careful, because the blank characters are ignored by the compiler. To solve, you would have to use another function to capture the String. But I believe it's not your case now.

        
    03.11.2017 / 02:54