【问题标题】:Writing A Cipher Program编写密码程序
【发布时间】:2013-02-05 17:27:18
【问题描述】:

编写一个从标准输入读取 ASCII 流的程序(过滤器) 并将字符发送到标准输出。该程序丢弃所有其他字符 比字母。任何小写字母都输出为大写字母。 以空格字符分隔的五个一组的输出字符。输出换行符 每 10 组后的字符。 (一行的最后一组后面只有换行符; 一行的最后一组后面没有空格。)最后一组可能 少于五个字符,最后一行可能少于 10 个组。假设输入文件是任意长度的文本文件。使用 getchar() 和 putchar() 为此。您永远不需要超过一个字符的输入数据 一次在记忆中

我遇到的问题是如何做间距。我创建了一个包含 5 个对象的数组,但我不知道如何处理它。这是我目前所拥有的:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

int main()
{
    char c=0, block[4]; 

    while (c != EOF)
    {
       c=getchar();

       if (isupper(c))
       {
           putchar(c);
       }
       if (islower(c))
       {
          putchar(c-32);
       }
    }
 }

【问题讨论】:

  • 闻起来像作业...

标签: c encryption


【解决方案1】:
int main()
{
    char c=0; 
    int charCounter = 0;
    int groupCounter = 0;

    while (c != EOF)
    {
       c=getchar();

       if (isupper(c))
       {
           putchar(c);
           charCounter++;
       }
       if (islower(c))
       {
          putchar(c-32);
          charCounter++;
       }

       // Output spaces and newlines as specified.
       // Untested, I'm sure it will need some fine-tuning.
       if (charCounter == 5)
       {
           putchar(' ');
           charCounter = 0;
           groupCounter++;
       }

       if (groupCounter == 10)
       {
           putchar('\n');
           groupCounter = 0;
       }
    }
 }

【讨论】:

【解决方案2】:

您无需存储字符即可执行问题中描述的算法。

您应该一次读取一个字符,并跟踪我不会透露的 2 个计数器。每个计数器都可以让您知道在哪里放置格式化输出所需的特殊字符。

基本上:

read a character
if the character is valid for output then
   convert it to uppercase if needed
   output the character
   update the counters
   output space and or newlines according to the counters
end if

希望这会有所帮助。

另外:我不知道你试图用 block 变量做什么,但它被声明为 4 个元素的数组,并且在文本中没有任何地方使用数字 4...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-22
    • 1970-01-01
    • 2016-08-11
    • 1970-01-01
    • 1970-01-01
    • 2020-08-22
    • 1970-01-01
    相关资源
    最近更新 更多