c++ - 如何将缓冲区中的字符串添加到另一个数组并打印出来?

标签 c++ c loops buffer fgets

所以基本上我想写一个词,当我按下回车键时,我想将这个字符串从缓冲区存储到数组。当我写第一个词时,它可能会起作用,但当我想添加第二个词时,它就变得很棘手了。

e.g.1st input is:first\0
    2nd input is:two\0
    then:Ctrl+Z(to get out of the loop)
    Output I want:first two (actually printing the 'array' array.)

我的代码在这里:

position=0;
printf("Enter a text: \n");
while(fgets(buffer, 100 , stdin) != NULL){
    for (i=position;i<(position+numberOfChars);i++){
        array[i]=buffer[i];
    }
    numberOfChars=strlen(buffer);
    position=position+numberOfChars+1;
}

最佳答案

查看代码中的注释:

position=0;
printf("Enter a text: \n");
while(fgets(buffer, 100 , stdin) != NULL){

    /* because you want to add space between 'first' and 'two' */ 
    if (position != 0) {
        array[position] = ' ';
        position++;
    }

    /* you need to get the buffer len for THIS iteration */
    numberOfChars=strlen(buffer);

    for (i=position;i<(position+numberOfChars);i++){
        /* i is a valid indice for array but not for buffer[0..numberOfChars-1] */
        /* array[i]=buffer[i]; */
        array[i] = buffer[i-position];
    }

    /* adding one will not add a space char */
    /* position=position+numberOfChars+1; */
    position = position+numberOfChars;
}

/* finaly add the null char at the end of the string (string is null terminated) */
array[position] = '\0';

你也可以试试这个:

printf("Enter a text: \n");

/* set array as an empty string */
array[0] = 0;

/* read from stdin */
while(fgets(buffer, 100, stdin) != NULL) {

    /* append a space to array if it isn't empty */
    if (array[0] != 0) 
        strcat(array, " ");

    /* append buffer to array */
    strcat(array, buffer)
}

/* print resulting array */
printf("%s\n");

关于c++ - 如何将缓冲区中的字符串添加到另一个数组并打印出来?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34190835/

相关文章:

c - 编译时 libcurl 错误(负值)

c++ - 了解 ostream 重载

c++ - 用窗口坐标绘制正方形

c - 为什么 Frama-C 的这个使用 scanf() 的程序的依赖图看起来像这样?

python - 如何编写 JIT 库?

javascript - 为什么我的函数没有循环且没有错误显示?

python - For循环没有正确迭代

java - 问 : Doing multiple loops and multiple if-statements and if-else-statements || RENTAL CAR CALCULATOR PROJECT

c++ - 为什么 std::get 没有接受转发引用的单一签名

C++ 模板, undefined reference