c++ - 在 C++ 中使用 std::vector 访问元素(get 和 put)

标签 c++ file vector

我正在尝试使用 vector 操作文件 (.txt) 的元素 - 例如 push_backaccessing [] 等。我想要对我从文件中检索到的元素执行简单的编码,虽然最终结果不是我所期望的,但我部分成功了。

这是文件内容(示例):

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/

相关文章:

C++ 继续与中断

file - 将文件复制到生成的jar中(在:jar Task之后)

c++ - 我的solve(字符串a,字符串b)的输出与Shuffle Hashing中的预期输出不匹配

C++从文本文件中读取并分离成 vector

c++ - GLM Math lib 使用 GCC 编译错误

c++ - 初始化和赋值

c++ - 如何在 Qt QML 中以声明方式更改文本颜色

c - 在文本文件中搜索电子邮件

xml - music21格式流为ABC+并保存为文件

c++ - 动态矩阵和 C++ : Segmentation Fault