我有一个名为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");
}
答案 0 :(得分:1)
您没有在外部循环中重新初始化x
和alphacount
。您的代码应如下所示:
while(!fin.eof())
{
int alphacount=0;
char ch, x='A';
fin >> ch;
.
.
.
调试器会在比编写问题所花费的时间更短的时间内为您找到此问题。
答案 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;
}
}
您根本不需要x
,因为您可以直接使用算术计算alphacount
。
您可以在alphacount
循环中移动while
。
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;
}
}