0

I'm taking my fist steps in programming and i was trying to make a program that takes as imput your username and and prints it out as output. I wanted to implement an if statement that triggers when you imput spaces instead of characters inside the scanf, but i can't seem to get it working? is it possible to do or is it impossible for an array of characters? Thaks for your help!



char username[20]; //declares a 20 chars array for the username to be stored

printf("\nPlease input your Username\nUsername:"); //asks for the username
       
scanf("%s", &username); //inserts username inside array "username"
        
if(username == ' '){  //supposedly the guard to my if 
                   
            printf(("invalid imput"));
        
}

printf("%s",username);
Frost1801
  • 13
  • 2
  • 1
    `%s` always reads a word into the variable. It will never put a space there. – Barmar Oct 30 '20 at 22:08
  • `scanf("%s", &username)` invokes *undefined behavior* because `char(*)[20]` is passed where `char*` is expected. the `&` should be removed. – MikeCAT Oct 30 '20 at 22:10
  • So how can i stop my program when a space is given as imput? If i keep pressing space or enter it keeps going forever without recognising it as imput. – Frost1801 Oct 30 '20 at 22:12
  • @MikeCAT thanks, that fixed one of the warnings! I don't know why but it still doesn't trigger the if function with a space even with this edit – Frost1801 Oct 30 '20 at 22:16
  • As @Barmar has already said, using `scanf("%s"...` will never collect the leading space. You will have to use a different method to read from `stdin`. A [method to do that is here](https://stackoverflow.com/a/60269590/645128). – ryyker Oct 30 '20 at 22:18

0 Answers0