+ 1

How to take an input string containing a sentence with spaces in C programming

We cannot use the scanf() function since after the first space, other part of the string will be neglected. If gets() fuction used it says buffer overflow.

13th Nov 2019, 11:41 AM
Sudam Yasodya
Sudam Yasodya - avatar
3 Réponses
+ 6
Use fgets to prevent overflow... It takes 3 parameters... fgets(char *str,int n,File* stream) for ur case if ur array name is str, and u want to input 30 characters to be stored from console use... fgets(str, 30,stdin) ;
13th Nov 2019, 12:40 PM
Saurabh B
Saurabh B - avatar
+ 2
You can use `scanf` too, but care needed to be taken to prevent buffer overflow. // allocate 50 characters + 1 // for the string terminator char buffer[51] = {0}; // Read up to 50 characters into // <buffer> or until a \n is found scanf("%50[^\n]s", buffer); printf("%s\n", buffer); Look at this reference and scroll down to find negated scanset http://www.cplusplus.com/reference/cstdio/scanf/
13th Nov 2019, 2:17 PM
Ipang