[英]How do I read from a file into a 2d array?
我正在开发一个与用户玩匹配游戏的程序。 代码可以编译,但是当我尝试运行它时,出现的表中有垃圾值。
我的输入文件如下所示:
//p4data1.dat
A
F
B
D
C
E
F
B
D
E
A
C
//p4data2.dat
F
B
D
C
A
F
E
A
C
D
B
E
我当前的代码是:
void fileAndRandom(char letArr[][COLUMN], int rows, int columns) {
int random = rand() % 2 + 1;
ifstream readFile;
if(random == 1) {
readFile.open("p4data1.dat");
for(int i = 0; i < rows; i++) {
for(int k = 0; k < columns; k++) {
readFile >> letArr[i][k];
}
}
}else if(random == 2) {
readFile.open("p4data2.dat");
for(int b = 0; b < rows; b++) {
for(int a = 0; a < columns; a++) {
readFile >> letArr[b][a];
}
}
}
readFile.close();
}
我被困在如何阅读它。我也不能使用向量,因为我还没有被教导这样做。
好吧,没关系,在参考了我的其他一些程序后,我最终弄明白了。 我的代码最终看起来像这样:
void fileAndRandom(char letArr[][COLUMN], int rows, int columns) {
int random = rand() % 2 + 1;
ifstream readFile;
if(random == 1) {
readFile.open("p4data1.dat");
for(int i = 0; i < rows; i++) {
for(int k = 0; k < columns; k++) {
readFile >> letArr[i][k];
}
}
}else if(random == 2) {
readFile.open("p4data2.dat");
for(int b = 0; b < rows; b++) {
for(int a = 0; a < columns; a++) {
readFile >> letArr[b][a];
}
}
}
readFile.close();
}
我只是想太多了
这也是我第一次使用堆栈溢出,所以我不太确定应答系统是如何工作的,哈哈
您应该使用std::vector
而不是数组,因为std::vector
是一个可变大小的容器,而且您并不总是知道 input.txt 文件包含多少个元素。 下面的完整工作程序显示了如何从文本文件中读取并将该信息存储在2D std::vector
中
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include<fstream>
int main() {
std::string line, word;
std::ifstream inFile("input.txt");
//create/use a std::vector instead of builit in array
std::vector<std::vector<std::string>> vec;
if(inFile)
{
while(getline(inFile, line, '\n'))
{
//create a temporary vector that will contain all the columns
std::vector<std::string> tempVec;
std::istringstream ss(line);
//read word by word
while(ss >> word)
{
//std::cout<<"word:"<<word<<std::endl;
//add the word to the temporary vector
tempVec.push_back(word);
}
//now all the words from the current line has been added to the temporary vector
vec.emplace_back(tempVec);
}
}
else
{
std::cout<<"file cannot be opened"<<std::endl;
}
inFile.close();
//lets check out the elements of the 2D vector so the we can confirm if it contains all the right elements(rows and columns)
for(std::vector<std::string> &newvec: vec)
{
for(const std::string &elem: newvec)
{
std::cout<<elem<<" ";
}
std::cout<<std::endl;
}
/*another way to print out the elements of the 2D vector would be as below
for(int row = 0; row < vec.size(); ++row)
{
for(int col = 0; col < vec.at(row).size(); ++col)
{
std::cout<<vec.at(row).at(col)<<" ";
}
std::cout<<std::endl;
}
*/
return 0;
}
以上程序的output可以看这里。 在我的程序结束时,我打印了二维向量的元素,以便我们可以确认它是否正确包含所有元素。
使用 std::vector 的优点是您不必事先知道输入文件中的行数和列数,也不需要传递(或分配 memory for) row
和column
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.