c - *C* 可接受的二维字符串输入?

标签 c string getchar

这是将数字串输入二维数组的好方法吗?我对代码有几个问题:

  • 任务是输入尽可能多的字符串,直到用户输入空字符串为止。然后我需要稍后对字符串进行标记化atoi

  • 使用一维数组和 char ** 会更好/更容易吗?

  • 最后,对于 char **,如果我为字符串分配内存,我是否必须为标记分配更多/不同的内存?

    int strInput ( char string[][], int maxChars )
    {
    int i = 0;
    
    printf("Enter strings of digits. Enter empty string to stop.\n");
    while (( string[i][maxChars] = getchar() )
    {
        printf("Please enter a string of digits:");
        i++;
    }
    string[i] = '\0';
    
    return i;
    }
    

最佳答案

char string[][] K&R 表示法很古老,您确实应该使用"new"char** 样式。

Is this an okay way to input strings of digits into a 2D array?

绝对不是。您正在逐个字符读取字符,而不是逐个数字字符串读取数字字符串,我认为您的意图是这样。

Would it be better / easier to use 1D array and a char ** to do it?

也可以那样做,在同一个字符串中的项目之间写一些标记。这基本上取决于您。

And last, with the char **, if I allocate memory for the strings, do I have to allocate more / different memory for the tokens?

是的,当然,您要么预先分配非常大的内存,要么不断重新分配。

关于c - *C* 可接受的二维字符串输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27329530/

相关文章:

c++ - 寻找用于简单协议(protocol)实现的库

C变量实例化速度

c - 如何设计一个可扩展到恰好 n 个元素的哈希函数?

c++ - 为什么 std::string 不能在用户输入中占用空格?

C: 简单复制输入 (getchar) 到输出 (printf) 返回额外的行

c++ - 为什么 getchar_unlocked() 比其他方法更快?

c - 意外的静态变量地址行为

c - 将参数传递给函数并进行转换

ruby - 罗莎琳德:SUBS 在给定的案例中失败了

c - 如何停止输入字符卡在缓冲区中? C