Taking String input with space in C (4 Different Methods)

We can take string input in C using scanf(“%s”, str). But, it accepts string only until it finds the first space.
There are 4 methods by which the C program accepts a string with space in the form of user input.
Let us have a character array (string) named str[]. So, we have declared a variable as char str[20].

Method 1 : Using gets
Syntax : char *gets(char *str)

C

char str[20]; printf ( "%s" , str);

Note : gets() has been removed from c11. So it might give you a warning when implemented.
We see here that it doesn’t bother about the size of the array. So, there is a chance of Buffer Overflow.

Method 2 : To overcome the above limitation, we can use fgets as :
Syntax : char *fgets(char *str, int size, FILE *stream)
Example : fgets(str, 20, stdin); as here, 20 is MAX_LIMIT according to declaration.

C

#define MAX_LIMIT 20 char str[MAX_LIMIT]; fgets (str, MAX_LIMIT, stdin); printf ( "%s" , str);

Method 3 : Using %[^\n]%*c inside scanf
Example : scanf(“%[^\n]%*c”, str);

C

char str[20]; scanf ( "%[^\n]%*c" , str); printf ( "%s" , str);

Explanation : Here, [] is the scanset character. ^\n tells to take input until newline doesn’t get encountered. Then, with this %*c, it reads newline character and here used * indicates that this newline character is discarded.

Method 4 : Using %[^\n]s inside scanf.

Example : scanf(“%[^\n]s”, str);

C

char str[100]; scanf ( "%[^\n]s" ,str); printf ( "%s" ,str);

Explanation : Here, [] is the scanset character. ^\n tells to take input until newline doesn’t get encountered. Here we used ^ (XOR -Operator ) which gives true until both characters are different. Once the character is equal to New-line (‘\n’), ^ (XOR Operator ) gives false to read the string. So we use “%[^\n]s” instead of “%s”. So to get a line of input with space we can go with scanf(“%[^\n]s”,str);

This article is contributed by Mukesh patel.

Aditya Kumar Like Article -->

Please Login to comment.

Similar Reads

Count pairs of points having distance between them equal to integral values in a K-dimensional space

Given an array points[] representing N points in a K-dimensional space, the task is to find the count of pairs of points in the space such that the distance between the points of each pair is an integer value. Examples: Input: points[] = < <1, 2>, , >, K = 2Output: 1Explanation: Distance between points of the pair(points[0], points[1])

7 min read Hiding of all Overloaded Methods with Same Name in Base Class in C++

In C++, function overloading is possible i.e., two or more functions from the same class can have the same name but different parameters. However, if a derived class redefines the base class member method then all the base class methods with the same name become hidden in the derived class. For example, the following program doesn't compile. Here,

3 min read Linking Files having same variables with different data types in C

Suppose there are two codes foo1.c and foo2.c as below and here the task is to link foo1.c and foo2.c which have same variable name x but different data type i.e int in foo1.c and double in foo2.c. Note that none of the variables is declared as extern. What do you expect to be the output of the following command with given two programs? $ gcc -o my

2 min read Different ways to Initialize all members of an array to the same value in C

An array is a collection of data that holds fixed number of values of same type. For example: if you want to store marks of 100 students, you can create an array for it. int num[100]; How to declare an array in C? Data_type array_name[size_of_array]; For example, float num[10]; Below are some of the different ways in which all elements of an array

3 min read Code valid in both C and C++ but produce different output

There are some syntactical structures that are valid for both C and C++ but different behavior when compiled and run in the both languages. Several differences can also be exploited to create code that compile in both languages but behave differently. For example, the following function will return different values in C and C++: Example Codes valid

2 min read Different Ways to Setting Up Environment For C++ Programming in Mac

Xcode is an IDE developed by Apple themselves to develop apps for macOS and iOS or all other Operating Systems that Apple develops. It also has support for C/C++ built-in. Here, finding a C++ IDE for a macOS system is quite easy. To run a program in C++ in Mac we have to install Xcode or command-line tools for Xcode. Ways: Hence, there are two opti

3 min read Write a program that produces different results in C and C++

Write a program that compiles and runs both in C and C++, but produces different results when compiled by C and C++ compilers. There can be many such programs, following are some of them. 1) Character literals are treated differently in C and C++. In C character literals like 'a', 'b', ..etc are treated as integers, while as characters in C++. (See

2 min read Print 2D matrix in different lines and without curly braces in C/C++?

Following is a general way of printing 2D matrix such that every row is printed in separate lines. C/C++ Code for (int i = 0; i &lt; m; i++) < for (int j = 0; j &lt; n; j++) < cout &lt;&lt; arr[i][j] &lt;&lt; &quot; &quot;; >// Newline for new row cout &lt;&lt; endl; > How to print without using any curly br

2 min read Print colored message with different fonts and sizes in C

In C/C++ we can use graphics.h header file for creation of programs which uses graphical functions like creating different objects, setting the color of text, printing messages in different fonts and size, changing the background of our output console and much more. Here we will create a program which will print message ("geeks") in colored form in

2 min read Different ways to declare variable as constant in C

There are many different ways to make the variable as constant in C. Some of the popular ones are: Using const KeywordUsing MacrosUsing enum Keyword1. Using const KeywordThe const keyword specifies that a variable or object value is constant and can't be modified at the compilation time. Syntaxconst data_type variable_name = initial_value;ExampleTh

2 min read C | Input and Output | Question 13

Predict the output of following program? #include "stdio.h" int main() < char arr[100]; printf("%d", scanf("%s", arr)); /* Suppose that input value given for above scanf is "GeeksQuiz" */ return 1; >(A) 9 (B) 1 (C) 10 (D) 100 Answer: (B) Explanation: In C, scanf returns the no. of inputs it has successfully

1 min read C | Input and Output | Question 2

Predict output of the following program C/C++ Code #include int main() < printf("\new_c_question\b\r"); printf("geeksforgeeks"); getchar(); return 0; >(A) ew_c_questiongeeksforgeeks (B) new_c_quesgeeksforgeeks (C) geeksforgeeks (D) Depends on terminal configuration Answer: (D) Explanation: See https://stackoverflow.com/questions/17236242/usage-of-

1 min read C | Input and Output | Question 3

#include <stdio.h> int main() < printf(" \"GEEKS %% FOR %% GEEKS\""); getchar(); return 0; >(A) “GEEKS % FOR % GEEKS” (B) GEEKS % FOR % GEEKS (C) \"GEEKS %% FOR %% GEEKS\" (D) GEEKS %% FOR %% GEEKS Answer: (A) Explanation: Backslash (\\\\) works as escape character for double quote (“). For explanation of %%, see https://

1 min read C | Input and Output | Question 4

C/C++ Code #include // Assume base address of \"GeeksQuiz\" to be 1000 int main() < printf(5 + \"GeeksQuiz\"); return 0; >(A)GeeksQuiz (B)Quiz (C)1005 (D)Compile-time error Answer: (B)Explanation: printf is a library function defined under stdio.h header file. The compiler adds 5 to the base address of the string through the expression 5 + \"Geeks

1 min read C | Input and Output | Question 5

Predict the output of the below program: C/C++ Code #include int main() < printf(\"%c \", 5[\"GeeksQuiz\"]); return 0; >(A) Compile-time error (B) Runtime error (C) Q (D) s Answer: (C) Explanation: The crux of the program lies in the expression: 5[\"GeeksQuiz\"] This expression is broken down by the compiler as: *(5 + \"GeeksQuiz\"). Adding 5 to t

1 min read C | Input and Output | Question 6

Predict the output of below program: #include <stdio.h> int main() < printf("%c ", "GeeksQuiz"[5]); return 0; >(A) Compile-time error (B) Runtime error (C) Q (D) s Answer: (C) Explanation: The crux of the program lies in the expression: "GeeksQuiz"[5]. This expression is broken down by the compiler as: *(“GeeksQuiz” + 5).

1 min read C | Input and Output | Question 9

What does the following C statement mean? C/C++ Code scanf(\"%4s\", str); (A)Read exactly 4 characters from console. (B)Read maximum 4 characters from console. (C)Read a string str in multiples of 4 (D)Nothing Answer: (B)Explanation: Try following program, enter GeeksQuiz, the output would be \"Geek\" #include <stdio.h> int main() < char str[

1 min read C | Input and Output | Question 13

#include<stdio.h> int main() < char *s = "Geeks Quiz"; int n = 7; printf("%.*s", n, s); return 0; >(A) Geeks Quiz (B) Nothing is printed (C) Geeks Q (D) Geeks Qu Answer: (C) Explanation: .* means The precision is not specified in the format string, but as an additional integer value argument preceding the argument that ha

1 min read C | Input and Output | Question 11

Predict the output of following program? #include <stdio.h> int main(void) < int x = printf("GeeksQuiz"); printf("%d", x); return 0; >(A) GeeksQuiz9 (B) GeeksQuiz10 (C) GeeksQuizGeeksQuiz (D) GeeksQuiz1 Answer: (A) Explanation: The printf function returns the number of characters successfully printed on the screen. The st

1 min read C | Input and Output | Question 12

Output of following program? #include<stdio.h> int main() < printf("%d", printf("%d", 1234)); return 0; >(A) 12344 (B) 12341 (C) 11234 (D) 41234 Answer: (A) Explanation: printf() returns the number of characters successfully printed on the screen.Quiz of this Question

1 min read C | Input and Output | Question 13

What is the return type of getchar()? (A) int (B) char (C) unsigned char (D) float Answer: (A) Explanation: The return type of getchar() is int to accommodate EOF which indicates failure:Quiz of this Question

1 min read Input an integer array without spaces in C

How to input a large number (a number that cannot be stored even in long long int) without spaces? We need this large number in an integer array such that every array element stores a single digit. Input : 10000000000000000000000000000000000000000000000 We need to read it in an arr[] = <1, 0, 0. 0>In C scanf(), we can specify count of digits t

2 min read How to input or read a Character, Word and a Sentence from user in C?

C is a procedural programming language. It was initially developed by Dennis Ritchie as a system programming language to write an operating system. The main features of the C language include low-level access to memory, a simple set of keywords, and a clean style, these features make C language suitable for system programmings like operating system

4 min read Formatted and Unformatted Input/Output functions in C with Examples

This article focuses on discussing the following topics in detail- Formatted I/O Functions.Unformatted I/O Functions.Formatted I/O Functions vs Unformatted I/O Functions.Formatted I/O Functions Formatted I/O functions are used to take various inputs from the user and display multiple outputs to the user. These types of I/O functions can help to dis

9 min read Input-output system calls in C | Create, Open, Close, Read, Write

System calls are the calls that a program makes to the system kernel to provide the services to which the program does not have direct access. For example, providing access to input and output devices such as monitors and keyboards. We can use various functions provided in the C Programming language for input/output system calls such as create, ope

10 min read How to use getline() in C++ when there are blank lines in input?

In C++, if we need to read a few sentences from a stream, the generally preferred way is to use the getline() function as it can read string streams till it encounters a newline or sees a delimiter provided by the user. Also, it uses <string.h> header file to be fully functional. Here is a sample program in c++ that reads four sentences and d

2 min read getchar_unlocked() – Faster Input in C/C++ For Competitive Programming

getchar_unlocked() is similar to getchar() with the exception that it is not thread-safe. This function can be securely used in a multi-threaded program if and only if they are invoked when the invoking thread possesses the (FILE*) object, as is the situation after calling flockfile() or ftrylockfile(). Syntax: int getchar_unlocked(void); Example:

2 min read Clearing The Input Buffer In C/C++

What is a buffer? A temporary storage area is called a buffer. All standard input and output devices contain an input and output buffer. In standard C/C++, streams are buffered. For example, in the case of standard input, when we press the key on the keyboard, it isn’t sent to your program, instead of that, it is sent to the buffer by the operating

6 min read Basic Input and Output in C

C language has standard libraries that allow input and output in a program. The stdio.h or standard input output library in C that has methods for input and output. scanf()The scanf() method, in C, reads the value from the console as per the type specified and store it in the given address. Syntax: scanf("%X", &variableOfXType);where %X is the

3 min read Print all possible combinations of the string by replacing '$' with any other digit from the string

Given a number as a string where some of the digits are replaced by a '$', the task is to generate all possible number by replacing the '$' with any of the digits from the given string.Examples: Input: str = "23$$" Output: 2322 2323 2332 2333Input: str = "$45" Output: 445 545 Approach: Find all the combinations of the string by replacing the charac