Reading string from input with space character? [d

2019-01-01 06:16发布

This question already has an answer here:

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?

14条回答
刘海飞了
2楼-- · 2019-01-01 06:54

Try this:

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

\n just sets the delimiter for the scanned string.

查看更多
梦醉为红颜
3楼-- · 2019-01-01 06:55

The correct answer is this:

#include <stdio.h>

int main(void)
{
    char name[100];

    printf("Enter your name: ");
    // pay attention to the space in front of the %
    //that do all the trick
    scanf(" %[^\n]s", name);
    printf("Your Name is: %s", name);

    return 0;
}

That space in front of % is very important, because if you have in your program another few scanf let's say you have 1 scanf of an integer value and another scanf with a double value... when you reach the scanf for your char (string name) that command will be skipped and you can't enter value for it... but if you put that space in front of % will be ok everything and not skip nothing.

查看更多
余生无你
4楼-- · 2019-01-01 06:58

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.

查看更多
其实,你不懂
5楼-- · 2019-01-01 07:00
scanf(" %[^\t\n]s",&str);

str is the variable in which you are getting the string from.

查看更多
皆成旧梦
6楼-- · 2019-01-01 07:06

Using this code you can take input till pressing enter of your keyboard.

char ch[100];
int i;
for (i = 0; ch[i] != '\n'; i++)
{
    scanf("%c ", &ch[i]);
}
查看更多
姐姐魅力值爆表
7楼-- · 2019-01-01 07:07
scanf("%s",name);

use & with scanf input

查看更多
登录 后发表回答