我编写了这个程序,用“*”替换两个空格。
如何修改代码,以便无论字符串大小如何,它都能执行相同的操作?是否可以仅使用 putchar
和 getchar
?
#include <stdio.h>
int c;
char buffer[256];
int counter= 0;
int i;
int main()
{
while ((c = getchar()) != '\n'&&c!=EOF) {
buffer[counter] =c;
counter++;
if (counter >=255) {
break;
}
}
for(i=0; i<256; i++) {
if(buffer[i]== ' '&&buffer[i+1]==' ')
{
buffer[i]= '*';
putchar(buffer[i]);
i = i + 2;
continue;
}
putchar(buffer[i]);
}
putchar('\n');
return 0;
}
最佳答案
问题陈述不要求您将完整的输入存储在缓冲区中。输出什么字符的决定仅取决于输入的最后两个字符。考虑以下代码:
#include <stdio.h>
int main(void)
{
// two variables for the last two input characters
int c = EOF, last = EOF;
while ((c = getchar()) != EOF)
{
// if both are a space, store a single '*' instead
if (c == ' ' && last == ' ')
{
c = '*';
last = EOF;
}
// print the output, and shift the buffer
if (last != EOF)
putchar(last);
last = c;
}
// take care of the last character in the buffer after we see EOF
if (last != EOF)
putchar(last);
}
根本不需要 malloc 和 friend 。这是一个很好的例子,说明了一个问题,要求您在编写代码之前仔细思考,以免在缓冲区上浪费不必要的资源。
关于c - 输入长度未知的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49829314/