c - 如何在C中读取一行中的多个字符串,每个字符串都包含空格?

标签 c string malloc c-strings gets

我分配了一个二维字符数组,在读取之间没有空格的字符串时,代码运行良好。当我用空格阅读它们时,我遇到了一个错误。如何读取所有 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/

相关文章:

c - 在结构中使用寄存器

c - 重命名函数而不更改其引用

Python将文本拆分为列表

c - memcpy 在这个程序中到底做了什么?

c - 为什么要在 c 中关闭管道?

c++ - 我该如何解决CUDA编程中的 fatal error C1070:文件中的#if/#endif对不匹配?

c# - 字符串值不能通过类方法赋值

java.lang.String(String original) 记录不充分

ruby - 在 Mac OS X 上调试 Ruby 中的 malloc 错误

c - 使用动态数组时增加内存