Click here to Skip to main content
15,891,136 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello everyone!!!

I'm trying to give a string as input using C.

When I give for example "Hello world" as input , I receive "Hello" only without "World".Why is this happening and how can I solve it???

What I have tried:

C++
int main(void)
{   
    char *A = "Player_1";
    char *B = "Player_2";
    char *word_A = malloc(sizeof(char) * 50);
    char *word_B = malloc(sizeof(char) * 50);
    word_A = get_word(A,B);
    printf("Word_A => %s\n" , word_A);
    word_B = get_word(B,A);
    printf("Word_B => %s\n" , word_B);
}



char *get_word(char *player_A , char *player_B)
{
    char *word = malloc(50);
    printf("%s give a word without %s looking at it: " , player_A , player_B);
    scanf("%s" , word);
    return word;
}


I also tried scanf("%[^\n]" , word); ,but then I can't input for second time and program terminates.What can I do???

Thanks...
Posted
Updated 8-Sep-20 11:01am

 
Share this answer
 
Once I'd tidied up a little, and fixed the (modern compiler enforced) errors, it works fine:
C++
#include <iostream>
char *get_word(const char *player_A , const char *player_B);
int main(void)
    {   
    const char *A = "Player_1";
    const char *B = "Player_2";
    char *word_A;
    char *word_B;
    word_A = get_word(A,B);
    printf("Word_A => %s\n" , word_A);
    word_B = get_word(B,A);
    printf("Word_B => %s\n" , word_B);
    }



char *get_word(const char *player_A , const char *player_B)
    {
    char *word = (char*) malloc(50);
    printf("%s give a word without %s looking at it: " , player_A , player_B);
    scanf("%s" , word);
    return word;
    }

The thing to note is that scanf terminates input on whitespace, not just newline: C library function - scanf() - Tutorialspoint[^] - so "hello world" will be read as two inputs: "hello" and "world".
If you want to read the whole line, you will need to use C library function - fgets() - Tutorialspoint[^] instead.
 
Share this answer
 
v4

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900