我有一个名为 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");
}
最佳答案
我看到的东西:
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; } }
您根本不需要
x
,因为您可以直接使用算术计算alphacount
。您可以在
while
循环内移动alphacount
。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/