我正在尝试使用 vector 操作文件 (.txt
) 的元素 - 例如 push_back
、accessing []
等。我想要对我从文件中检索到的元素执行简单的编码,虽然最终结果不是我所期望的,但我部分成功了。
这是文件内容(示例):
datum
-6353
argo
我想在这里执行的是读取 vector (有点像二维)的每个元素,并用它们各自的 ASCII
代码对它们进行编码。
这是我的代码(到目前为止):
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <iterator>
using namespace std;
int main ()
{
std::string word;
//std::vector<std::vector <std::string> > file;
std::vector<std::string> file;
std::ifstream in( "test.txt" );
while (in >> word)
{
file.push_back(word);
}
for (size_t i=0; i<file.size(); i++)
{
for (int j=0;j<file[i].size();j++)
{
//cout<<i<<","<< j<<endl;
cout<<((int)file[i][j])<<",";
}
}
in.close();
return 0;
}
当前输出(对于上述代码):
100,97,116,117,109,45,54,51,53,51,97,114,103,111,
RUN FINISHED; exit value 0; real time: 0ms; user: 0ms; system: 0ms
预期输出:
100,97,116,117,109
45,54,51,53,51
97,114,103,111
请指导我实现这一目标。
最佳答案
在第一次循环后尝试 cout << endl
for (size_t i=0; i<file.size(); i++)
{
for (int j=0;j<file[i].size();j++)
{
//cout<<i<<","<< j<<endl;
cout<<((int)file[i][j])<<",";
}
**cout << endl;**
}
关于c++ - 在 C++ 中使用 std::vector 访问元素(get 和 put),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20796097/