如果這個問題看起來有點愚蠢,我很抱歉,但即使我已經嘗試了很多次,我也無法讓它作業。所以我的問題是,我有一個文本檔案,里面有一個數字,如下所示:
10 20 30
30 40 50
60 70 80
數字、行大小和列大小是來自用戶的輸入。到目前為止,我已經為所有這些撰寫了代碼。這意味著用戶可以輸入行大小、列大小和整數。但我無法從這個檔案讀入一個陣列。我能為此做什么?
uj5u.com熱心網友回復:
注意,在C 中,一個內置的陣列的大小必須是一個編譯時間常數。因此,您不能將行和列作為用戶的輸入,然后將這些變數用作內置陣列的大小。
甲更好替代方法是使用2Dvector如下所示。在陣列上使用 a的優點vector是您不需要事先指定(知道)行和列。也就是說,文本輸入檔案可以有多少行和列,而無需詢問用戶該檔案有多少行和列。std::vector將處理它,如下所示。
下面的程式使用 2Dstd::vector以 2D 方式存盤資訊(如本例中的整數值)。從檔案中讀取所有值后,您可以根據需要處理向量。顯示的程式int從input.txt讀取資料(值)并將它們存盤在 2D 中vector。此外,即使列數奇數,該程式也能作業。您可以使用以下程式作為參考(起點)。
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include<fstream>
int main() {
std::string line;
int word;
std::ifstream inFile("input.txt");
//create/use a std::vector instead of builit in array
std::vector<std::vector<int>> vec;
if(inFile)
{
while(getline(inFile, line, '\n'))
{
//create a temporary vector that will contain all the columns
std::vector<int> tempVec;
std::istringstream ss(line);
//read word by word(or int by int)
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();
//now you can do the whatever processing you want on the vector
//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<int> &newvec: vec)
{
for(const int &elem: newvec)
{
std::cout<<elem<<" ";
}
std::cout<<std::endl;
}
return 0;
}
上面程式的輸出可以在這里看到。上面提到的鏈接中還提供了讀取 int 值的輸入檔案。
使用矢量的優勢
您不需要詢問用戶輸入檔案中的行數和列數。
即使在任何特定行中有不均勻的條目,上述程式也能正常作業。
std::vector為您處理記憶體管理。所以你不必自己使用new和使用delete,需要更多的關注/照顧。
uj5u.com熱心網友回復:
二維向量解決方案非常好。但是如果你不想使用向量,你也可以使用二維動態陣列。如果您特別想輸入行和列并從檔案中讀取,這里還有一個解決方案,您可以在其中使用 2d 動態陣列。這對您來說是一個有點高級的概念,因為它包含在 C OOP 中,但是您可以根據您的要求輕松地從 .txt 檔案中讀取到二維陣列中。
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
void main()
{
int rows=0,cols=0;
cout<<"Enter your rows: ";
cin>>rows;
cout<<"Enter your rows: ";
cin>>cols;
int** arr= new int*[rows];
for(int k=0;k< rows; k )
arr[k]= new int[cols];
ifstream read_num;
read_num.open("matrix.txt");
if(read_num.is_open())
{
for(int x=0;x<rows; x )
{
for(int y=0;y<cols; y )
{
read_num>>arr[x][y];
}
}
}
else
cout<<"Failed to open file"<<endl;
cout<<"After reading data from file:"<<endl;
for(int x=0; x<rows; x )
{
for(int y=0; y< cols; y )
{
cout<<arr[x][y]<<" ";
}
cout<<endl;
}
read_num.close();
for (int i = 0; i < rows; i )
{
delete [] arr[i];
}
delete[] arr;
system("pause");
}
這段代碼的輸出可以在這里看到,代碼中的輸入檔案被命名為matrix.txt。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/373622.html
上一篇:指標參考在C 中是如何作業的?
