【问题标题】:Using Functions and Arrays to Read and Print Data from a File使用函数和数组从文件中读取和打印数据
【发布时间】:2013-12-04 07:07:31
【问题描述】:

我对 C++ 比较陌生,我的教授给了我们一个我似乎无法弄清楚的作业。

我们应该编写可以读取文件并将值打印到屏幕的函数。然后我们应该能够从文件中打印出最大值。这听起来很简单,但我似乎无法让它工作。

它可以编译,但我把它作为我的输出:

0023F908-858993460-858993460-858993460-858993460-858993460-858993460-858993460-8
58993460-858993460-858993460-858993460-858993460-858993460-858993460-858993460-8
58993460-858993460-858993460-858993460-8589934600023F908-858993460-858993460-858
993460-858993460-858993460The largest value is 0
Press any key to continue . . .

任何建议将不胜感激!

这是文件包含的内容:

4 5

3 1 4 1 5

2 3 6 7 1 

7 8 8 8 8 

9 8 7 6 5

这是我目前所拥有的:

void printValue( const ChartType, int, int);

int main () 
{ 
 ChartType chart; 
 int rowsUsed; 
 int colsUsed; 
 ifstream dataIn; 
 dataIn.open("Chart.txt"); 
 GetChart(dataIn, chart, rowsUsed, colsUsed); 
 PrintChart(chart, rowsUsed, colsUsed); 
 printValue(chart, rowsUsed, colsUsed);
 return 0; 
} 

void GetChart(ifstream& data, ChartType chart, int& rowsUsed, int& colsUsed) 
{ 
int tempVariable;
 data >> rowsUsed >> colsUsed; 
 for (int row = 0; row < rowsUsed; row++) 
    for (int col = 0; col < colsUsed; col++) 
        data >> chart[4][5];
        data >> tempVariable;
        chart[rowsUsed][colsUsed] = tempVariable;
 } 

void PrintChart( const ChartType chart, int rowsUsed, int colsUsed) 
{ 
 cout << chart[rowsUsed];
 for (int row = 0; row < rowsUsed; row++) 
 { 
 for (int col = 0; col < colsUsed; col++) 
 cout << chart[row][col]; 
 } 
}

 void printValue( const ChartType chart, int rowsUsed, int colsUsed) 
{ 
 int largest = 0;
 int row = 0;
 int col = 0;
 cout << chart[rowsUsed];
 for ( ; row < rowsUsed; row++) 
 { 
 for ( ; col < colsUsed; col++) 
 cout << chart[row][col];

 if (chart[row][col] > largest)
     largest = chart[row][col];
 }
 cout << "The largest value is " << largest << endl;
 } 

【问题讨论】:

  • 您还应该添加为什么它不起作用?我的意思是它的输出是什么?
  • 哎呀,对不起!这是我第一次来这里。谢谢!
  • 没有伤害。欢迎来到 SO。
  • @user3064666 文件是否存在?流可以打开吗?在阅读之前,您必须通过调用bool std::basic_ios::good() 来检查它。也告诉我们ChartType定义
  • data &gt;&gt; chart[4][5]; ???此外,for 循环仅影响以下语句,除非 {} 包围多个语句,因此 data &gt;&gt; tempVariable;chart[rowsUsed][colsUsed] = tempVariable;for 循环完成后运行。您可能尝试复制到 chart[row][col] 并遇到编译器错误...那是因为 rowcol 仅存在于它们的 for 循环范围内。

标签: c++ arrays file function


【解决方案1】:

据我所知,GetChart 函数是错误的。 试试这个,

void GetChart(ifstream& data, ChartType chart, int& rowsUsed, int& colsUsed) 
{ 
    data >> rowsUsed >> colsUsed; 
    for (int row=0; row<rowsUsed; ++row) 
        for (int col=0; col<colsUsed; ++col) 
            data >> chart[row][col];
}

【讨论】:

  • +1 是朝着正确方向迈出的一步,但鉴于 rowsUsedcolsUsed 只是刚刚阅读,没有明确调整 chart 的大小以确保它足够大以完成索引在chart[row][col]。如果没有看到ChartType 的实现,我们就无法知道需要什么(operator[] 自动调整大小的可能性很小)。
  • 你可以跳过临时变量,直接做data &gt;&gt; chart[row][col]
猜你喜欢
  • 2017-12-30
  • 1970-01-01
  • 2021-04-17
  • 2021-06-05
  • 2011-11-22
  • 1970-01-01
  • 2023-04-09
  • 1970-01-01
相关资源
最近更新 更多