Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/60.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用scanf从没有空格的用户处获取字符串?_C_Scanf - Fatal编程技术网

如何使用scanf从没有空格的用户处获取字符串?

如何使用scanf从没有空格的用户处获取字符串?,c,scanf,C,Scanf,这是一个C代码,用于从用户处获取括号“()”&“&”&“{}”和“[]”类型的字符串。此字符串的长度为n,它是用户输入 int main() { long int n; int i; scanf("%lld", &n); char array[n]; for(i=0; i<n ; i++) { scanf("%s", &array[i]); } } intmain() { 长整数n; int i; scanf(“%lld”、&n);

这是一个C代码,用于从用户处获取括号“()”&“&”&“{}”和“[]”类型的字符串。此字符串的长度为n,它是用户输入

int main()
{
  long int n;
  int i;
  scanf("%lld", &n);
  char array[n];
  for(i=0; i<n ; i++)
  {
     scanf("%s", &array[i]);
  }
 }
intmain()
{
长整数n;
int i;
scanf(“%lld”、&n);
字符数组[n];
对于(i=0;i变化:

scanf("%s", &array[i]);
为此:

scanf(" %c", &array[i]);
因为你要做的是一个字符一个字符地读取你的字符串

char c; for (i = 0; i < n; i++) { c = '\0'; while (c != ' ') // wait for the user to type a space character { scanf ("%s", &c); } while (c == ' ') // wait for the user to type something else { scanf ("%s", &c); } array[i] = c; } 请注意
%c
之前的空格,它将使用从您输入
n
时开始留在stdin缓冲区中的尾随换行符

我曾经写过在使用
scanf()
读取字符时的注意事项

现在,即使您对输入使用
{(()
{(()
),也将是相同的,因为
scanf()
将忽略空白

但是,如果您想让标准函数使用字符串(几乎肯定需要),则应该以null结尾。例如,如果要使用
printf(“%s”,array);
,则必须以
array
null结尾

一种方法是,假设用户输入正确(在完美世界中),您可以这样做:

#include <stdio.h>
int main()
{
  long int n;
  int i;
  scanf("%ld", &n);

  // create an extra cell to store the null terminating character
  char array[n + 1];

  // read the 'n' characters of the user
  for(i=0; i<n ; i++)
  {
     scanf(" %c", &array[i]);
  }

  // null terminate the string
  array[n] = '\0';

  // now all standard functions can be used by your string
  printf("%s\n", array);

  return 0;
 }
#包括
int main()
{
长整数n;
int i;
scanf(“%ld”、&n);
//创建一个额外的单元格来存储空终止字符
字符数组[n+1];
//读取用户的“n”字符

对于(i=0;i
scanf(“%ld”,&n);
。请使用编译器的警告!它会告诉您这一点。

如果要确保用户在每个“有效”字符之间至少键入一个空格字符,您可以在循环中等待,直到用户添加空格字符

char c; for (i = 0; i < n; i++) { c = '\0'; while (c != ' ') // wait for the user to type a space character { scanf ("%s", &c); } while (c == ' ') // wait for the user to type something else { scanf ("%s", &c); } array[i] = c; } 字符c; 对于(i=0;i< n;i++) { c='\0'; while(c!=“”)//等待用户键入空格字符 { scanf(“%s”、&c); } while(c='')//等待用户键入其他内容 { scanf(“%s”、&c); } 数组[i]=c; }
scanf(“%s”、&array[i]);
更改为
scanf(“%c”、&array[i]);
我已经尝试过了。输出会发生变化并出错。但是空格问题通过这种方式得到了解决。这是因为
\n
被遗留下来。要使用新行,请在
%c
之前添加空格。像这样
scanf(“%c”、&array[i]));
@Andromeda是一个很好的问题,有一个完整的最小示例!请务必阅读我的更新答案,因为空终止字符串!希望这对我有帮助。@gsamaras我已经阅读了它。非常感谢您的帮助:)