gpt4 book ai didi

c - 从控制台读取正好 50 个字符(49 +1 表示 null),仅忽略所有初始空格

转载 作者:行者123 更新时间:2023-12-02 01:42:39 26 4
gpt4 key购买 nike

我如何从控制台中的用户输入中读取恰好 50 个字符(49 个字符,+1 表示 null),忽略所有初始空格(如第一个单词之前)但之后保留 49 个字符,包括所有空格?

此外,如果用户输入的字符少于 49 个字符并输入换行符,它只会处理该字符(换行符之前的所有内容都会忽略初始空格)。

我尝试使用:

char name[50];
scanf("%49s",name);

但是,这似乎忽略了所有空白;所以,如果我的名字是这样的:“Mark Smith”,它将无法正确处理。

最佳答案

您可以在输入格式说明符前添加一个(单个)空格,以跳过任何/所有前导空白字符,然后使用 [set] format specifier (前面有“49”限制)输入与给定“集合”匹配的所有后续字符。在您的情况下,该集合可以是除了换行符之外的任何内容,因此在集合之前使用“not”前缀 (^),并使集合包含 >只是换行符(\n):

#include <stdio.h>

int main()
{
char name[50];
printf("Enter input: ");
int n = scanf(" %49[^\n]", name);
if (n != 1) {
printf("Input error!");
}
else {
printf("Input was: %s\n", name);
}
return 0;
}

测试:

Enter input:        I am the egg-man; I am the egg-man; I am the walrus!
Input was: I am the egg-man; I am the egg-man; I am the walr

请注意,使用上述代码,如果输入的输入字符串超过 49 个字符,则多余的字符将留在输入缓冲区中。这些很可能会导致进一步的问题,因为它们将被用作对 scanf(或类似输入函数)的任何后续调用的输入。

有多种方法可以“清除”输入缓冲区:How to clear input buffer in C?简要总结链接问题的答案:

  1. 永远不要使用(或尝试使用)fflush(stdin)
  2. 代码如 the following一种典型的方式是:
int c;
while ( (c = getchar()) != '\n' && c != EOF ) { }

关于c - 从控制台读取正好 50 个字符(49 +1 表示 null),仅忽略所有初始空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71400617/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com