努力將單詞存盤在 2D 陣列中,當我使用char 時它作業正常但是當我使用下面的邏輯來存盤字串時,我感到困惑
代碼:
string word;
int rows ,column;
string arr[10][20];
fstream myFile("name.txt");
while(myFile>>word)
{
arr[rows][column]=word;
}
在這里,我被困在區分黑白行和列的演算法是什么。
名稱.txt:
It's steve
Studying CPP
and steve loves cooking
另外,一旦找到微分演算法,我想將此檔案的出現顯示為二維陣列
uj5u.com熱心網友回復:
您應該使用std::vector而不是陣列,因為它std::vector是一個可變大小的容器,并且您并不總是知道 input.txt 檔案包含多少個元素。完整的作業程式下面展示了如何實作你想要使用的是什么2Dstd::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;
}
上面程式的輸出可以在這里看到。在我的程式結束時,我列印了2d 向量的元素,以便我們可以確認它是否正確包含了所有元素。
uj5u.com熱心網友回復:
好吧,首先,我認為您忘記初始化rows和column。但除此之外,strings 自己管理字符陣列,因此您不需要它們的 2D 陣列,而是一個簡單的 1D 陣列。
像這樣:
string word;
int rows = 0;
string arr[10];
fstream myFile("name.txt");
while(myFile>>word)
{
arr[rows] = word;
rows ;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/342693.html
下一篇:用字典陣列過濾字典陣列
