[英]Using atoi() and printing a string fail - C
I want to write a program that it will read a couple of strings, convert one of them to an integer using the atoi() and then printing another.我想编写一个程序,它将读取几个字符串,使用 atoi() 将其中一个转换为整数,然后打印另一个。
This is my code:这是我的代码:
#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;
}
So my problem is that it doesnt exit the while loop if i enter 0 as an input the second time i do the process.所以我的问题是,如果我第二次输入 0 作为输入,它不会退出 while 循环。 Moreover, it does not print the names correctly in the end... What can i do?
此外,它最终没有正确打印名称......我该怎么办? (Take in consideration that i am an amateur :D) Thank you for your help!
(考虑到我是业余爱好者 :D)感谢您的帮助!
Insufficient space for the string.字符串空间不足。 @barak manos
@巴拉克马诺斯
When the following code attempts to read 5 char
into afm[i]
, it invokes undefined behavior as a keyboard entry of 5 char
like "abcde" and Enter , attempts to store 'a'
, 'b'
, 'c'
, 'd'
, 'e'
, '\\0'
into afm[i]
.当以下代码尝试将 5 个
char
读入afm[i]
,它会调用未定义的行为作为 5 个char
的键盘输入,例如 "abcde" 和Enter ,尝试存储'a'
、 '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]);
The above is a an example of the problem of using gets()
, which is no longer standard in C11.上面是使用
gets()
的问题的一个例子,它在 C11 中不再是标准的。
Instead use fgets()
.而是使用
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.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.