Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading string from input with space character? [duplicate]

I'm using Ubuntu and I'm also using Geany and CodeBlock as my IDE. What I'm trying to do is reading a string (like "Barack Obama") and put it in a variable:

#include <stdio.h>  int main(void) {     char name[100];      printf("Enter your name: ");     scanf("%s", name);     printf("Your Name is: %s", name);      return 0; } 

Output:

Enter your name: Barack Obama Your Name is: Barack 

How can I make the program read the whole name?

like image 994
Hieu Nguyen Avatar asked Jun 08 '11 16:06

Hieu Nguyen


People also ask

How do you read string inputs with spaces?

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);

How do I print a string with spaces?

Program Explanation Get a String using fgets() function. Str -> reads the string and stores it in str. 50 -> reads maximum of 50 characters stdin-> reads character from keyboard using for loop print all characters one by one. "%c " in printf prints character with space.

How do you read a string with spaces in Python?

Python String isspace() Method The isspace() method returns “True” if all characters in the string are whitespace characters, Otherwise, It returns “False”. This function is used to check if the argument contains all whitespace characters such as: ' ' – Space. '\t' – Horizontal tab.


2 Answers

Use:

fgets (name, 100, stdin); 

100 is the max length of the buffer. You should adjust it as per your need.

Use:

scanf ("%[^\n]%*c", name); 

The [] is the scanset character. [^\n] tells that while the input is not a newline ('\n') take input. Then with the %*c it reads the newline character from the input buffer (which is not read), and the * indicates that this read in input is discarded (assignment suppression), as you do not need it, and this newline in the buffer does not create any problem for next inputs that you might take.

Read here about the scanset and the assignment suppression operators.

Note you can also use gets but ....

Never use gets(). Because it is impossible to tell without knowing the data in advance how many characters gets() will read, and because gets() will continue to store characters past the end of the buffer, it is extremely dangerous to use. It has been used to break computer security. Use fgets() instead.

like image 133
phoxis Avatar answered Oct 06 '22 07:10

phoxis


Try this:

scanf("%[^\n]s",name); 

\n just sets the delimiter for the scanned string.

like image 29
Sridhar Iyer Avatar answered Oct 06 '22 06:10

Sridhar Iyer