我正在对 Traveling Knight 问题进行非常简单的 BFS 搜索。不幸的是,我的输入决定出错。这段代码给出了正确的结果。
char start[2], destination[2];
scanf("%s", start); // input string is "e2"
printf("%d %d\n", start[0], start[1]); // start[0] = 101, start[1] = 50
(in ASCII, 101 is 'e' and 50 is '2')
我用的那个
scanf("%s", start); // input string is "e2"
scanf("%s", destination); // input string is "e4"
printf("%d %d\n", start[0], start[1]); // start[0] = 0, start[1] = 50
或
scanf("%s %s", start, destination); // input string is "e2 e4"
printf("%d %d\n", start[0], start[1]); // start[0] = 0, start[1] = 50
但目标数组不会出现这种错误。我做错什么了吗?如果这是一个错误,我可以使用替代方法吗?
编辑:起点声明为 char[2],目标也一样。中南合作中心
void main()
{
char start[2], destination[2];
scanf("%s", start); // input string is "e2"
scanf("%s", destination); // input string is "e4"
printf("%d %d\n", start[0], start[1]); // start[0] = 101, start[1] = 50
}
最佳答案
四件事。
void main()
不是标准的。它应该返回一个int
- 您的字符缓冲区不够大。
- 将您
scanf()
到数组的任何字符串的长度限制为小于数组大小。那个权利会向你暗示你的缓冲区太小了。“%1s”
嗯.... - 在依赖它们之前验证您的
scanf()
结果。
也就是说,
#include <stdio.h>
#include <stdlib.h>
int main()
{
int res = EXIT_FAILURE;
char start[3], destination[3];
if (scanf("%2s", start) == 1 &&
scanf("%2s", destination) == 1)
{
printf("%d %d\n", start[0], start[1]);
res = EXIT_SUCCESS;
}
return res;
}
关于c - 第一个 scanf ("%s") 在使用第二个 scanf ("%s") 时中断,读取 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19261100/