【问题标题】:Storing words of specific file in 2D Array C++在 2D Array C++ 中存储特定文件的单词
【发布时间】:2021-12-15 01:06:07
【问题描述】:
努力将单词存储在 2D 数组中,当我使用 char 时效果很好,但是当我使用下面的逻辑存储 string 时,我感到困惑
代码:
string word;
int rows ,column;
string arr[10][20];
fstream myFile("name.txt");
while(myFile>>word)
{
arr[rows][column]=word;
}
在这里,我不知道用于区分黑白行和列的算法是什么。
name.txt:
It's steve
Studying CPP
and steve loves cooking
另外,一旦我找到微分算法,我想将此文件的出现显示为二维数组
【问题讨论】:
标签:
c++
arrays
multidimensional-array
file-handling
【解决方案1】:
您应该使用std::vector 而不是数组,因为std::vector 是一个可变大小的容器,您并不总是知道 input.txt 文件包含多少个元素。完整的工作程序 below 展示了如何使用 2D std::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;
}
上面程序的输出可以看到here。在我的程序结束时,我打印出了 2d 矢量 的元素,以便我们可以确认它是否正确包含所有元素。
【解决方案2】:
嗯,首先,我想你忘了初始化rows 和column。但除此之外,strings 自己管理字符数组,因此您不需要为它们提供 2D 数组,而需要一个简单的 1D 数组。
像这样:
string word;
int rows = 0;
string arr[10];
fstream myFile("name.txt");
while(myFile>>word)
{
arr[rows] = word;
rows++;
}