从c++文件中获取输入(矩阵数组输入)
Getting input from a file C++ (Matrix Array Input)
我将让用户输入一个包含如下数据的文件:
<>以前numRowsnumCols……x……x...…之前现在我有麻烦从这样的文件读取数据。我不明白我应该怎么做才能从每行读取每个整数。这是我目前所看到的:
#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)变量?
我想将文件的前两行分别保存为numRows
和numCols
,然后在每行之后的每个整数将是矩阵的一个单元格值。示例输入:
TIA
试试这个。第一行读取路径。然后,使用freopen
将提供的文件与stdin
关联。因此,现在我们可以直接使用cin
操作,就像我们直接从stdin
中读取一样,就像从文件中逐行输入到控制台一样。
在此之后,我创建了numRows
和numCols
对应的两个变量,并创建了这个维度的矩阵。然后我创建一个嵌套的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];
相关文章:
- 遇到此问题时遇到困难:允许用户输入数组的值并使用 for,而循环也输出输入的最大数字
- C++逗号分隔的输入数组代码过早退出
- 如何输入数组的元素,每次获得新元素时,我们将其放在数组的中间?
- 使用STL对用户输入数组进行排序的错误有什么解决方案吗?
- 使用 cin 输入数组值
- 与 C++ 中一行中的用户输入数组元素相关的问题
- 将整数输入数组的方法比 scanf() 或 cin 更快?
- 如何在C 中动态输入数组
- 我想添加两个字符串类型的矩阵.用户将不会输入行数或列的数量.用户将仅输入数组
- 测试用户输入数组中的重复项的最有效方法是什么?
- 在用户输入数组中查找元音
- 如何将用户输入数组值移动到数组末尾并将其设置为 0
- 函数是否可以用较小的输入数组编写输入数组
- C++ 将数字输入数组并输出
- 需要帮助传递数组和输入数组
- 用户输入数组大小(N).从 0 到 N 的数字填充数组
- 输入int之后的字符的c++输入数组
- 合并排序 - 返回新数组,而不是将合并的数组复制到输入数组
- 在C 函数中声明输入数组的大小
- 在 cpp 中使用 getline 输入数组中的空格分隔数字