[英]Getting input from a file C++ (Matrix Array Input)
我會讓用戶輸入一個文件,其中包含一些這樣的數據:
numRows numCols x x x ... x x x 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
,然后在每行的每個整數之后將是矩陣的單元格值。 樣本輸入:
2 2 1 2 3 4
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];
請參閱此以獲取更多參考。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.