【发布时间】: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 < 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", &date, &slash, &month, &slash, &year);始终检查来自scanf()的返回值,以确保所有输入/转换都成功。
标签: c visual-studio printing atoi