在C++中将ASCII读取到数组中

Read ASCII into array in C++

本文关键字:数组 读取 ASCII C++ 中将      更新时间:2023-10-16

我是C++的新手,无法找到完成这项看似简单的任务的方法。我有一个ascii文件,只包含制表符分隔的数字,类似于:

1    2    5    6
8    9    1    3 
5    9    2    3

我需要简单地使用c++将这个行一行地加载到一个数组中。什么是简单的方法?提前感谢!Niccolo

我无法发表评论,因为我还没有50的声誉,但我会尽我所能帮助你找到答案。

这需要对C++和循环有基本的理解。我认为最好的方法是同时使用std::vector(因为您提到了C++)。

  • std::fstream
  • std::vector<char>
  • char
  • std::noskipws
  • vector.push_back

示例程序流程:

  1. 打开输入流
  2. 检查它是否打开
  3. 逐字符循环输入并使用std::noskipws
  4. 在循环中,使用vector.push_back
  5. 记得关闭输入流

示例代码:

#include <iostream>
#include <fstream>
#include <vector>
int main(int argc, char *argv[])
{
    //Use std::fstream for opening and reading the file.txt
    std::fstream Input("file.txt", std::fstream::in);
    //If the input stream is open...
    if(Input.is_open())
    {
        //...Create variables
        char ch;
        std::vector<char> cVector;
        //Loop trough the Input, character by characted and make use of std::noskipws
        while(Input >> std::noskipws >> ch) 
        {
            //Push the char ch to the vector
            cVector.push_back(ch);
        }
        //This is for looping through the vector, and printing the content as it is
        for(auto i : cVector)
        {
            std::cout << i;
        }
        //Remember to close the input
        Input.close();
    }
    //Prevent application from closing instantly
    std::cin.ignore(2);
    return 0;
}

希望我帮了你,这就解决了问题。但如果下次你能解释一下你遇到了什么问题,以及你尝试了什么,我将不胜感激。

谨致问候,Okkaaj