Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Programming — get multiple words in string

I am trying to get a full sentence eg. "This is a sentence." to be stored in the global variable string named 'global'. It will then print out the sentence back out. However after entering my input, I can only get the first word of the sentence printed (This). Anyone got any ideas?

#include <string.h>

char** global;

int main () {

    printf("Please Enter Text: \n");
    scanf("%s", &global);

    printf("%s", &global);


    return 0;
}
like image 319
NewFile Avatar asked Dec 07 '25 20:12

NewFile


1 Answers

The char** global should be char* global only.

& with printf is not required.

You need to use fgets(var_name,no_of_chars,FILE*) in place of scanf.

fgets(global,100,stdin); //where global is char global[100]; 

Example :

Use of gets is more serious then i was thinking. So it's no longer recommended.

A Better one

char global[100];    
int main () {
    printf("Please Enter Text: \n");
    if(fgets(global,50,stdin)) //It will take Maximum 50 chars. So no buffer overflow. 
    fputs(global,stdout);
    return 0;
}
like image 139
Arpit Avatar answered Dec 09 '25 10:12

Arpit