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