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

时间:2014-04-07 20:35:02

标签: c++ function

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

TIGER 狗 CAT

需要输出

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

IIIIIIIII IIIIIIIII(I 2x9,因为它是第2个字符,第9个字母)

我已经尝试设置函数来执行此操作,但我的输出有点疯狂,一次输出一个字符的TONS,我很确定甚至不做行。我做错了什么?

#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");
}

2 个答案:

答案 0 :(得分:1)

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

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

    fin >> ch;
    .
    .
    .

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

答案 1 :(得分:1)

我看到的事情:

  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. 您可以在alphacount循环中移动while

  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;
       }
    }