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 07:09
#include<stdio.h>
int main()
{
   char name[100];
   printf("Enter your name: ");
   scanf("%[^\n]s",name);
   printf("Your Name is: %s",name);
   return 0;
}
查看更多
时光乱了年华
3楼-- · 2019-01-01 07:10

If you need to read more than one line, need to clear buffer. Example:

int n;
scanf("%d", &n);
char str[1001];
char temp;
scanf("%c",&temp); // temp statement to clear buffer
scanf("%[^\n]",str);
查看更多
登录 后发表回答