【发布时间】:2020-01-26 03:26:55
【问题描述】:
所以我想编写一个程序来检查用户是否输入。假设要求是 4 位数字,如果用户输入 5,那么程序会不断要求用户准确租用 4 位数字。
我得到了这样的工作代码:基本上使用scanf 读取字符串值,然后使用strlen 计算位数。如果用户输入了正确的数字,那么我使用atoi 将该字符串转换为int,稍后我将使用它。
假设要求是 4 位数字:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main() {
int digit, mynumber;
int digit = 5;
char str[5];
/* Checking if enter the correct digit */
do {
printf("Enter a %d digit number\n", digit);
scanf("%s", &str);
if (strlen(str) != digit) {
printf("You entered %d digits. Try again \n", strlen(str));
} else {
printf("You entered %d digits. \n", strlen(str));
printf("Converting string to num.....\n");
mynumber = atoi(str);
printf("The number is %d\n", mynumber);
}
} while (strlen(str) != digit);
return 0;
}
我想稍微修改一下。而不是对 5 位字符串执行 char str[5]。我想尝试一个动态数组。
所以代替 char str[5],我这样做:
char *str;
str = malloc(sizeof(char) * digit);
通过代码运行它会产生段错误。谁能帮我这个?
这是问题的完整代码
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main() {
int mynumber;
int digit = 5;
char *str;
str = malloc(sizeof(char) * digit);
/* Checking if enter the correct digit */
do {
printf("Enter a %d digit number\n", digit);
scanf("%s", &str);
if (strlen(str) != digit) {
printf("You entered %d digits. Try again \n", strlen(str));
} else {
printf("You entered %d digits. \n", strlen(str));
printf("Converting string to num.....\n");
mynumber = atoi(str);
printf("The number is %d\n", mynumber);
}
} while (strlen(str) != digit);
return 0;
}
【问题讨论】:
-
你能显示有问题的代码吗?我怀疑您将
str的地址传递给scanf,但没有代码,这只是猜测。 -
你需要
malloc(digit+1)。字符串 NUL 终止符需要一个额外的字节。 -
我刚刚添加了给出问题的完整代码。
-
你需要
scanf("%s", str);不&因为str已经是一个指针。 -
char str[5]; ... scanf("%s", &str);应该使用scanf("%4s", str);。如果代码需要读取超过 4 个字符,请使用更大的缓冲区。
标签: c string integer malloc atoi