【问题标题】:Using atoi() and printing a string fail - C使用 atoi() 并打印字符串失败 - C
【发布时间】:2015-11-29 16:17:18
【问题描述】:

我想编写一个程序,它会读取几个字符串,使用 atoi() 将其中一个转换为整数,然后打印另一个。

这是我的代码:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define N 3

int main() {
    char Name[N][20], Sname[N][20], afm[N][5];
    int i = 0;
    char slash;
    int date, month, year;
    int afmi;

    while (1) {

        printf("Give a 5-digit number: ");
        gets(afm[i]);

        afmi = atoi(afm); //Converting the afm string to an integer

        if (afmi == 0) { /*Getting out of the while loop as soon as the afm                                                              string gets 0 as an input. */
            break;
        }

        printf("Give your name: ");
        gets(Name[i]);

        printf("Give your Surname: ");
        gets(Sname[i]);

        printf("Birth date: "); //dd/mm//yy format
        scanf("%d%c%d%c%d", &date, &slash, &month, &slash, &year);
        getchar();


        i++;
    }

    for (i = 0; i <= N+1; i++) {  /*Here i want to print all the names i have input, one under another*/ 
        printf("name: %s \n", Name);
    }

    system("pause");
    return 0;
}

所以我的问题是,如果我在第二次执行该过程时输入 0 作为输入,它不会退出 while 循环。此外,它最终没有正确打印名称......我该怎么办? (考虑到我是业余爱好者:D) 感谢您的帮助!

【问题讨论】:

  • for (int j = 0; j &lt; i; j++) { printf("name: %s\n", Name[j]); }
  • 从不使用过时的gets。至少使用fgets,最好使用getline
  • afm[i] 不能表示以空字符结尾的 5 个字符的字符串!!!将afm[N][5] 更改为afm[N][6]
  • afmi = atoi(afm); -->afmi = atoi(afm[i]);
  • 关于这一行:scanf("%d%c%d%c%d", &amp;date, &amp;slash, &amp;month, &amp;slash, &amp;year); 始终检查来自scanf() 的返回值,以确保所有输入/转换都成功。

标签: c visual-studio printing atoi


【解决方案1】:

字符串空间不足。 @barak manos

当以下代码尝试将 5 char 读入 afm[i] 时,它会调用未定义的行为作为 5 char 的键盘输入,如“abcde”和 Enter,尝试存储 @ 987654325@、'b''c''d''e''\0' 转为afm[i]

// Bad code
#define N 3
char afm[N][5];
    printf("Give a 5-digit number: ");
    gets(afm[i]);

以上是使用gets()的问题示例,在C11中不再标准。

改为使用fgets()

  printf("Give a 5-digit number: ");
  char buf[80];
  if (fgets(buf, sizeof buf, stdin) == NULL) Handle_EOF();
  afmi = atoi(buf);  // or strtol() for better error handling.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-20
    • 2021-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多