使用函数输出字符串或字符.菜鸟



我有一个名为 animals.dat 的输入文件,我需要我的程序以块格式读取和输出文件。 例如,该文件显示:

老虎狗猫

它需要输出

TTTTTTTTTTTTTTTTTTTT(T 将是 1x20,因为它是单词中的第一个字符和字母表中的第 20 个字母)

三IIIIIIIII(I 2x9,因为它是字母表中的第2个字符和第9个字符)

我尝试设置函数来执行此操作,但我的输出有点疯狂,一次只输出大量一个字符,而且我很确定甚至没有做行。 我做错了什么?

#include "stdafx.h"
#include <iostream>
#include <fstream>
using namespace std;
ifstream fin;
ofstream fout;
void rectangle(char ch, int alphacount,int count) {
int height=1, width=0;
while(width <= alphacount && height <= count) {
    while(width <= alphacount) {
        fout << ch;
        cout << ch;
        width++;
    }
    cout << endl;
    if(height <= count) {
        fout << ch << endl;
        cout << ch << endl;
        height++;
    }
}
}
int main(void) {
 fin.open("animals.dat");
fout.open("out.dat");
 int count=0, alphacount=0;
 char ch, x='A';
 while(!fin.eof()) {
    fin >> ch;
    while(x!=ch) {
        x++;
        alphacount++;
    }
    rectangle(ch, alphacount, count);
    count++;
    if(ch =='n') {
        alphacount = 0;
        count = 0;
        x = 0;
    }
}
system("pause");
}

我看到的东西:

  1. 功能rectangle可以轻松简化。您只需要两个for循环。

    void rectangle(char ch, int alphacount,int count)
    {
       for ( int height = 0; height < count; ++height )
       {
          for ( int width = 0; width < alphacount; ++width )
          {
             fout << ch;
             cout << ch;
          }
          cout << endl;
       }
    }
    
  2. 您根本不需要x因为您可以使用算术直接计算alphacount

  3. 您可以在while循环内移动alphacount

  4. while循环中的代码可以简化为:

    while(!fin.eof())
    {
       int alphacount = 0;
       count++;
       char ch;
       fin >> ch;
       if ( isalpha(ch) )
       {
          if ( ch > 'Z' )
          {
             // It's a lower case letter.
             alphacount = ch - 'a' + 1;
          }
          else
          {
             // It's an upper case letter.
             alphacount = ch - 'A' + 1;
          }
          rectangle(ch, alphacount, count);
       }
       if(ch =='n')
       {
          count = 0;
       }
    }
    

您不会在外部循环中重新初始化xalphacount。您的代码应如下所示:

while(!fin.eof())
{
    int alphacount=0;
    char ch, x='A';
    fin >> ch;
    .
    .
    .

调试器会在比编写问题所花费的短得多的时间内为您找到此问题。

相关内容