c - 输入长度未知的字符串

标签 c arrays if-statement input

我编写了这个程序,用“*”替换两个空格。

如何修改代码,以便无论字符串大小如何,它都能执行相同的操作?是否可以仅使用 putchargetchar

#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/

相关文章:

c++ - Arduino:中断昂贵的功能并恢复另一个

javascript - 为什么我的 for 循环只运行一次 if 语句?

javascript - Vanilla JavaScript:如何搜索对象数组,键是数组

javascript if if else (not else if)

r - 如果满足条件,如何将值添加到前一行

c - C 中的列表和字符串问题

c - Visual Studio 编译单独的文件

Java 编译没有错误,运行第一行,然后不继续或结束

shell - For循环: how to limit the activity for just 1st occurance where there are multiple matches in the loop

ctime 没有正确获取循环开始/结束的时间差