打开文件功能麻烦

时间:2014-05-05 20:31:20

标签: c++

我是c ++编码的新手。我正在尝试编写一个打开指定“.txt”文件的函数(我厌倦了多次应对/粘贴)。我需要意识到:

  1. 指定文件名;
  2. 读取数据并保存到double(type)数组;
  3. return array;
  4. 据我所知,c ++不能返回数组,但它可以返回指针。问题是:如何使用它?任何帮助将不胜感激。 :)

    P.S我的草案代码(它正在运行):

    double arr[10];
    fstream file;
    file.open("input.txt");
    if(file.is_open()){
        while(file.good()){
            for(int i = 0 ; i < 10 ; i++){
                file >> arr[i];
            }
        }
        file.close();
    }else{ 
        cout<<"[ERROR]: File \"input.txt\" wasn't found!"<<endl;
        cout<<"[INFO]: Terminating program...";
        Sleep(1000);
        exit(0);
    }
    

1 个答案:

答案 0 :(得分:1)

  

我不知道怎么写作为一个函数。而且我不知道如何使用它

首先,试试这个:

std::vector<double> theFunction(const std::string &filename)
{
    std::vector<double> arr(10);

    std::fstream file(filename);

    if (file) 
    {
        for (int i = 0 ; i < 10 && file.good(); i++)
            file >> arr[i];
    }

    return arr;
}

std::vector<double> result = theFunction("input.txt");

if (result.empty())
    // Can not read the file
相关问题