我分配了一个二维字符数组,在读取之间没有空格的字符串时,代码运行良好。当我用空格阅读它们时,我遇到了一个错误。如何读取所有 N 个字符串,每个字符串都在一行中,每个字符串都包含空格。
输入示例:
Enter total number of Strings : 3
Enter all the 3 Strings :
John Doe
Jane Doe
Trad Braversy
我的代码:
// Code to enter the total number of Strings :
int N;
printf("\n\tEnter the total number of Strings : ");
scanf("%d", &N);
// Code for allocating initial memory to them :
char** strings = (char**)malloc(N * sizeof(char*));
for (int i = 0; i < N; ++i) {
strings[i] = (char*)malloc(1024 * sizeof(char));
}
// Code for entering all the N strings :
printf("\n\tEnter all the %d Strings :\n", N);
for (int i = 0; i < N; ++i) {
gets(strings[i]);
}
// Code to reallocate the memory according to the entered length :
for (int i = 0; i < N; ++i) {
strings[i] = (char*)realloc(strings[i], strlen(strings[i]) + 1);
}
最佳答案
一些观察:
读取整行文本,然后从中解析出整数比对单个整数执行 scanf()
更安全。这是因为后者在流中留下了换行符,这可能会混淆以后的读取。
使用malloc()
为此进行动态内存分配没有实际意义,您可以使用VLA:
char strings[N][1024];
请注意,在 C 语言中,对运行时变量使用仅大写的符号在风格上很奇怪。
那么,使用 fgets()
会更好 ,它更安全、更好:
for (int i = 0; i < N; ++i)
{
if (fgets(strings[i], sizeof strings[i], stdin) == NULL)
{
fprintf(stderr, "**Read error on string %d\n", i);
exit(1);
}
}
一如既往,做好 I/O 可能失败的准备,并尝试处理该问题。
关于c - 如何在C中读取一行中的多个字符串,每个字符串都包含空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59841965/