使用atoi()并打印字符串失败-C
我想写一个程序,它将读取几个字符串,使用atoi()将其中一个字符串转换为整数,然后打印另一个字符串 这是我的代码:使用atoi()并打印字符串失败-C,c,visual-studio,printing,atoi,C,Visual Studio,Printing,Atoi,我想写一个程序,它将读取几个字符串,使用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 da
#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;
}
#包括
#包括
#包括
#定义n3
int main(){
字符名[N][20]、Sname[N][20]、afm[N][5];
int i=0;
字符斜杠;
int日期、月份、年份;
国际非洲管理学院;
而(1){
printf(“给出一个5位数字:”);
获取(afm[i]);
afmi=atoi(afm);//将afm字符串转换为整数
如果(afmi==0){/*在afm字符串获得0作为输入时立即退出while循环*/
打破
}
printf(“说出你的名字:”);
获取(名称[i]);
printf(“说出你的姓氏:”);
获取(Sname[i]);
printf(“出生日期:”;//dd/mm//yy格式
scanf(“%d%c%d%c%d”、&date、&slash、&month、&slash、&year);
getchar();
i++;
}
对于(i=0;i字符串空间不足
当以下代码尝试将5char
读入afm[i]
时,它调用未定义的行为作为5char
的键盘输入,如“abcde”和Enter,尝试将'a'
,'b'
,'c'
,'d'
,'e'
,'e'
,'0'
存储到afm[i]/code>中
// Bad code
#define N 3
char afm[N][5];
printf("Give a 5-digit number: ");
gets(afm[i]);
上面是使用get()
问题的一个例子,这在C11中不再是标准
而是使用fgets()
for(int j=0;j
永远不要使用过时的get
。至少要使用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()返回的值,以确保所有输入/转换成功。
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.