如何使用scanf从没有空格的用户处获取字符串?
这是一个C代码,用于从用户处获取括号“()”&“&”&“{}”和“[]”类型的字符串。此字符串的长度为n,它是用户输入如何使用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);
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;iscanf(“%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我已经阅读了它。非常感谢您的帮助:)