用C ++将ASCII读入数组

时间:2014-09-09 12:35:44

标签: c++ arrays file ascii

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

1    2    5    6

8    9    1    3 

5    9    2    3

我需要简单地使用c ++将这一行逐行加载到数组中。什么是简单的方法呢? 提前致谢! 尼科洛

1 个答案:

答案 0 :(得分:0)

我无法发表评论,因为我还没有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. 请记住关闭输入流
  6. 示例代码:

    #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