【发布时间】:2019-08-07 03:06:33
【问题描述】:
我有一个介绍 C++ 课程的作业,我很困惑为什么我的 getline 似乎在工作,但它没有将我的函数输出到 outfile.txt。我的老师说我的 getline 语法不正确,但是我很困惑如何。
我的infile.txt 写着:
T & 4
S @ 6
T x 5
R * 5 7
D $ 7
D + 5
R = 4 3
E
还有我的代码:
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
void draw_rect (char out_char, int rows, int columns); // Draws a rectangle shape
void draw_square (char out_char, int rows); //Draws a square shape
void draw_triangle (char out_char, int rows);// Draws a triangle shape
void draw_diamond (char out_char, int rows); // Draws a diamond shape
int main()
{
ofstream outfile;
ifstream infile;
int row, col;
bool exit = false;
char value;
infile.open("infile.txt");
outfile.open("outfile.txt");
if(!infile.good())
{
cout << "failed to open\n";
}else
{
string buffer;
while(!infile.eof() || !exit)
{
getline(infile, buffer);
switch(buffer[0])
{
case 'R':
value = buffer[2];
row = buffer[4];
col = buffer[6];
draw_rect(value, row, col);
break;
case 'T':
value = buffer[2];
row = buffer [4];
draw_triangle(value, row);
break;
case 'D':
value = buffer[2];
row = buffer[4];
draw_diamond(value, row);
break;
case 'S':
value = buffer[2];
row = buffer[4];
draw_square(value, row);
break;
case 'E':
cout << "Files Written.\nExiting." << endl;
exit = true;
break;
default:
cout << "Invalid input, try again" << endl;
}
}
}
return 0;
}
void draw_diamond (char out_char, int rows)
{
ofstream outfile;
int space = 1;
space = rows - 1;
for (int i = 1; i <= rows; i++)
{
for (int k = 1; k <= space; k++)
{
outfile << " ";
}
space--;
for( int k = 1; k <= 2*i-1; k++)
{
outfile << out_char;
}
outfile << endl;
}
space = 1;
for (int i = 1; i <= rows; i++)
{
for(int k = 1; k <= space; k++)
{
outfile << " ";
}
space++;
for(int k = 1; k <= 2*(rows-i)-1; k++)
{
outfile << out_char;
}
outfile << endl;
}
}
void draw_triangle (char out_char, int rows)
{
ofstream outfile;
for (int i = 0; i < rows; i++)
{
for (int j = 0; j <= i; j++)
{
outfile << out_char;
}
outfile << endl;
}
}
void draw_square (char out_char, int rows)
{
ofstream outfile;
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < rows; j++)
{
outfile << out_char;
}
outfile << endl;
}
}
void draw_rect (char out_char, int rows, int columns)
{
ofstream outfile;
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
outfile << out_char;
}
outfile << endl;
}
}
【问题讨论】:
-
真诚地,奇怪的是你的老师没有指出问题出在哪里。我只是不明白这种教学是如何运作的。好吧。您不能假设在 main 函数中定义对象会神奇地初始化在本地函数中定义的对象。看
draw_diamond函数,你期望ofstream outfile会怎么初始化? -
C++ 很难学,因为它是。像这里描述的那样,完全不称职的教练不会让事情变得更容易。
标签: c++ file-io getline shapes