gpt4 book ai didi

c++ - 我的二维数组没有读取我的文本文件并正确输出

转载 作者:行者123 更新时间:2023-11-30 04:46:26 24 4
gpt4 key购买 nike

我希望能够将文本文件中的字母读入二维数组。我正在执行所有步骤,但我的输出完全不正确。

我尝试初始化数组,尝试更改 for 循环,尝试本地化我的 const int 值,但没有任何效果。

#include <iostream>
#include <iomanip>
#include <fstream>

using namespace std;



int main()
{
const int ROWS = 5;
const int COLS = 3;
ifstream inFile("grades.txt");

char gradeArray[ROWS][COLS] = {0};

inFile.open("grades.txt");

if (!inFile.is_open())
{
cout << "Error opening the file.";
exit(1);
}

for (int i = 0; i < ROWS; i++)
{
for (int j = 0; j < COLS; j++)
{
inFile >> gradeArray[i][j];
}
}
cout << gradeArray[0][1];


inFile.close();

system("pause");
return 0;
}

TXT 文件(我的资源文件中的 grades.txt)

编辑:每个字母都有自己的换行符。不确定为什么他们在同一个。

一个R乙CHGCF小号乙AA小号E

F

我希望输出字母“R”作为测试,因为这是我在最后一个 cout 语句中要求的,但我得到 [Press any key to continue 。 . .]。所以只是一个空间。请帮忙。谢谢!

到目前为止,我已经尝试了给我的建议,但没有奏效。我在想文件没有被正确读取?或者文件没有​​正确输出...

最佳答案

IIRC 做 inFile >> gradeArray[i][j]将捕获空白;您应该能够通过读入一个字符串而不是跳过空格来解决这个问题;只需添加 #include <string>在顶部然后在你的循环中读入字符串并将成绩作为第一个字符,比如

string line;
inFile >> line;
gradeArray[i][j] = line.empty() ? ' ' : line[0];

或您想要表示缺失数据的任何字符。

关于c++ - 我的二维数组没有读取我的文本文件并正确输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56745172/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com