c++ - 使用函数输出字符串或字符。小白

标签 c++ function

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

老虎 狗 猫

需要输出

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

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

关于c++ - 使用函数输出字符串或字符。小白,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22922555/

相关文章:

c++ - 关于值类和 vector 的问题

javascript - 事件和调用,何时使用,何时不使用?

python - 如何部分定义函数参数? Python

c - 如何在头文件和c文件中声明函数指针?

c - 我的阶乘函数和幂函数在不应该输出数百万的情况下输出了数百万,我不知道如何修复它(在 c 中)

javascript - HTML 表单中的 onClick JavaScript 函数

c++ - C++中是否有浮点文字后缀来使数字 double ?

c++ - Makefile,在src目录树中查找源代码并在构建文件中编译为.o

c# - 如何将字符串参数从 C++ com 传递给 C#?

c++ - valgrind 和 openmp,仍然可以访问并可能丢失,这很糟糕吗?