c - 第一个 scanf ("%s") 在使用第二个 scanf ("%s") 时中断,读取 0

标签 c string char scanf

我正在对 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 
}

最佳答案

四件事。

  1. void main() 不是标准的。它应该返回一个 int
  2. 您的字符缓冲区不够大。
  3. 将您 scanf() 到数组的任何字符串的长度限制为小于数组大小。那个权利会向你暗示你的缓冲区太小了。 “%1s”嗯....
  4. 在依赖它们之前验证您的 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/

相关文章:

c - 如何在 C 中创建我自己的字符串函数?

java - 什么是character,与char有什么区别? java

c - 为什么当偏移量为非负数(但是是 sysconf(_SC_PAGE_SIZE) 的倍数)时 mmap 会因 EINVAL 而失败?

c - 使用GDB调试时如何打印指针指向的字符串?

php - 如何使用 PHP 从字符串中删除子字符串?

javascript替换多个字符

c - char *str 为 null 和 str[0] == '\0' 有什么区别

c# - 为什么没有像 String.Empty 这样的 Char.Empty?

c - 将 libpcap 与套接字连接一起使用

c - 如何确保父进程先于子进程执行scanf()?