c++ - 在 2D Array C++ 中存储特定文件的单词
问题描述
努力将单词存储在二维数组中,当我使用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
另外,一旦我找到微分算法,我想将此文件的出现显示为 2D-Array
解决方案
您应该使用std::vector
而不是数组,因为std::vector
它是一个可变大小的容器,而且您并不总是知道 input.txt 文件包含多少元素。下面的完整工作程序显示了如何使用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;
}
上述程序的输出可以在这里看到。在我的程序结束时,我打印了二维向量的元素,以便我们可以确认它是否正确包含所有元素。
推荐阅读
- objective-c - 优化在 Obj C 中调用自身的函数
- asp.net - 如何将 EF CLass 库添加到适用于 .net 4.5 和 dotnet core 的解决方案中
- spring-boot - Spring Boot - 如何在登录前显示静态资源?
- java - 轮询 Pod 的就绪状态
- angular - NgFor 重复一个 div 表单并将输入分配给 NgModel
- android - 如何在 Gradle 3+ 上进行 ABI 拆分以更改版本代码?
- python - 如何获取 tensorflow 的预制估计器的图形定义
- file - 从预先格式化的 Golang 文件中读取
- java - spring-data-solr:单个集合中的多个存储库?
- javascript - 从页面上的元素中获取 URL 以缩短 Bitly URL