C语言 从带有空格字符的输入中读取字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6282198/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 08:52:29  来源:igfitidea点击:

Reading string from input with space character?

cstringinputscanfwhitespace

提问by Hieu Nguyen

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:

我使用的是 Ubuntu,我也使用 Geany 和 CodeBlock 作为我的 IDE。我想要做的是读取一个字符串(如"Barack Obama")并将其放入一个变量中:

#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?

如何让程序读取全名?

回答by phoxis

Use:

用:

fgets (name, 100, stdin);

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

100是缓冲区的最大长度。你应该根据你的需要调整它。

Use:

用:

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

The []is the scanset character. [^\n]tells that while the input is nota newline ('\n') take input. Then with the %*cit 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.

[]是字符扫描集。[^\n]告诉虽然输入不是换行符 ( '\n') 接受输入。然后用%*c它从输入缓冲区中读取换行符(未读取),并且*指示这个读入的输入被丢弃(赋值抑制),因为你不需要它,并且缓冲区中的这个换行符不会创建您可能会采取的下一个输入的任何问题。

Read here about the scansetand the assignment suppressionoperators.

在此处阅读有关scanset赋值抑制运算符的信息。

Note you can also use getsbut ....

请注意,您也可以使用gets但是 ....

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.

永远不要使用gets(). 因为在事先不知道数据的情况下是不可能知道gets()会读取多少个字符的,而且因为gets()会继续存储超过缓冲区末尾的字符,所以使用起来极其危险。它已被用来破坏计算机安全。使用fgets()来代替。

回答by Sridhar Iyer

Try this:

尝试这个:

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

\njust sets the delimiter for the scanned string.

\n只是为扫描的字符串设置分隔符。

回答by animesh

scanf(" %[^\t\n]s",&str);

stris the variable in which you are getting the string from.

str是从中获取字符串的变量。

回答by kyle k

Here is an example of how you can get input containing spaces by using the fgetsfunction.

下面是一个示例,说明如何使用该fgets函数获取包含空格的输入。

#include <stdio.h>

int main()
{
    char name[100];
    printf("Enter your name: ");
    fgets(name, 100, stdin); 
    printf("Your Name is: %s", name);
    return 0;
}

回答by Ritesh Sharma

NOTE: When using fgets(), the last character in the array will be '\n' at times when you use fgets() for small inputs in CLI (command line interpreter) , as you end the string with 'Enter'. So when you print the string the compiler will always go to the next line when printing the string. If you want the input string to have null terminated string like behavior, use this simple hack.

注意:当使用 fgets() 时,当您在 CLI(命令行解释器)中使用 fgets() 进行小输入时,数组中的最后一个字符将是 '\n',因为您以 'Enter' 结束字符串。因此,当您打印字符串时,编译器将始终在打印字符串时转到下一行。如果您希望输入字符串具有类似空终止字符串的行为,请使用这个简单的技巧。

#include<stdio.h>
int main()
{
 int i,size;
 char a[100];
 fgets(a,100,stdin);;
 size = strlen(a);
 a[size-1]='
char ch[100];
int i;
for (i = 0; ch[i] != '\n'; i++)
{
    scanf("%c ", &ch[i]);
}
'; return 0; }

Update: Updated with help from other users.

更新:在其他用户的帮助下更新。

回答by iFTEKHAR LIVE

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

使用此代码,您可以输入直到按下键盘的 Enter 键。

#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;
}

回答by Cristian Babarusi

The correct answer is this:

正确答案是这样的:

#include <stdio.h>
// read a line into str, return length
int read_line(char str[]) {
int c, i=0;
c = getchar();
while (c != '\n' && c != EOF) { 
   str[i] = c;
   c = getchar();
   i++;
}
str[i] = '
int n;
scanf("%d", &n);
char str[1001];
char temp;
scanf("%c",&temp); // temp statement to clear buffer
scanf("%[^\n]",str);
'; return i; }

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.

% 前面的空间非常重要,因为如果你的程序中有另外几个 scanf 假设你有一个整数值的 1 scanf 和另一个带有双值的 scanf ......当你到达你的字符(字符串名称)该命令将被跳过,您无法为其输入值...但是如果您将该空格放在 % 前面就可以了,并且不会跳过任何内容。

回答by ayush bhorse

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

回答by levan

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

如果需要读取多于一行,需要清空缓冲区。例子:

##代码##

回答by Pranta Palit

##代码##