gpt4 book ai didi

c++ - 从文件 C++ 获取输入(矩阵数组输入)

转载 作者:行者123 更新时间:2023-11-30 05:21:38 25 4
gpt4 key购买 nike

我会让用户输入一个包含如下数据的文件:

numRowsnumColsx x x ... x x x x ... x......

Now I am having trouble reading data from a file like this. I am not understanding what should I do to read each integer from each line. This is what I have so far:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

class my_exception : public std::exception {
virtual const char *what() const throw() {
return "Exception occurred!!";
}
};

int main() {

cout << "Enter the directory of the file: " << endl;
string path;
cin >> path;

ifstream infile;
cout << "You entered: " << path << endl;

infile.open(path.c_str());

string x;

try
{
if (infile.fail()) {
throw my_exception();
}
string line;

while (!infile.eof())
{
getline(infile, line);
cout << line << endl;
}
}
catch (const exception& e)
{
cout << e.what() << endl;
}

system("pause");
return 0;
}

另外我想要的是在每一行存储数据!这意味着在第一行之后我想将数据存储到相应的变量和每个单元格值中。

我对如何获取每个整数并将它们存储在唯一(numRows 和 numCols)变量中感到困惑?

我想将文件的前两行分别保存到 numRowsnumCols 中,然后在每一行之后的每个整数将是矩阵的一个单元格值。输入示例:

221 2 3 4

TIA

最佳答案

试试这个。第一行读取路径。然后,我们使用 freopen 将提供的文件与 stdin 相关联。所以现在我们可以直接使用 cin 操作,就好像我们直接从 stdin 读取一样,就好像文件的输入是逐行输入到控制台中一样。

在此之后,我创建了两个对应于 numRowsnumCols 的变量,并创建了这个维度的矩阵。然后我创建一个嵌套的 for 循环来读取矩阵的每个值。

string path;
cin >> path;
freopen(path.c_str(),"r",stdin);

int numRows, numCols;
cin >> numRows >> numCols;

int matrix[numRows][numCols];

for(int i = 0; i < numRows; i++){
for(int j = 0; j < numCols; j++){
cin >> matrix[i][j];
}
}

或者你可以用它来创建你的矩阵

int** matrix = new int*[numRows];
for(int i = 0; i < numRows; i++)
matrix[i] = new int[numCols];

参见 this以供更多引用。

关于c++ - 从文件 C++ 获取输入(矩阵数组输入),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39991579/

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