在C++中读取ASCII数组 我是C++新手,无法得到一个看似简单的任务。 我有一个ascii文件,其中只包含制表符分隔的数字,类似于: 1 2 5 6 8 9 1 3 5 9 2 3 我需要用C++将这行逐行加载到数组中。做这件事的简单方法是什么? 提前谢谢! 尼科洛

在C++中读取ASCII数组 我是C++新手,无法得到一个看似简单的任务。 我有一个ascii文件,其中只包含制表符分隔的数字,类似于: 1 2 5 6 8 9 1 3 5 9 2 3 我需要用C++将这行逐行加载到数组中。做这件事的简单方法是什么? 提前谢谢! 尼科洛,c++,arrays,file,ascii,C++,Arrays,File,Ascii,我无法发表评论,因为我还没有50%的声誉,但我会尽力通过回答来帮助你 这需要对C++和循环的基本理解。我看到的最好的方法是使用STD::向量,因为你提到C++。 std::fstream 向量 烧焦 std::noskipws 向量。推回 示例程序流: 开放输入流 检查它是否打开 逐个字符循环输入,并使用std::noskipws 在循环中,使用vector.push_back 记住关闭输入流 示例代码: #include <iostream> #include <fstrea

我无法发表评论,因为我还没有50%的声誉,但我会尽力通过回答来帮助你

<>这需要对C++和循环的基本理解。我看到的最好的方法是使用STD::向量,因为你提到C++。 std::fstream 向量 烧焦 std::noskipws 向量。推回 示例程序流:

开放输入流 检查它是否打开 逐个字符循环输入,并使用std::noskipws 在循环中,使用vector.push_back 记住关闭输入流 示例代码:

#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

您在读取文件时遇到问题吗?还是阵列有问题?你试过什么吗?还有,你用什么编译器?可能与c++11/14功能相关…嘿嘿!我正在使用visual studio 2012。我不太熟悉阅读文件与C++,所以我真的没有线索从哪里开始…将数字指定给数组而不是printf。您需要事先声明数组大小,或者存储有关文件第一行中有多少个数字的信息。通常情况下,如果您不知道要加载多少个元素,可以使用列表,而不是数组。您好,非常感谢您的帮助!我试过了,但它在第一次运行时存在循环。。。?再次感谢