【问题标题】:Reading file into array C++将文件读入数组 C++
【发布时间】:2021-01-03 21:35:39
【问题描述】:

我试图简单地将文件“input.txt”读入数组 people[]。 txt文件有3个数字:

10
20
30

对于人[0],我得到 -9.25596e+61 而不是 10。这是我的代码:

#include <iostream>
#include <string>
#include <fstream>

using namespace std;

class Trip {
private:

    double people[3];

public:
    void readFile(string file);
};

void Trip::readFile(string file) {
    ifstream input;
    input.open(file);
    input >> people[0] >> people[1] >> people[2];
    cout << people[0];
    input.close();

}



int main() {
    Trip trip;
    trip.readFile("input.txt");
    return 0;
}

【问题讨论】:

  • 您应该检查文件是否实际打开,或者cin是否因任何原因失败。
  • 提示:在 C++ 中使用 std::vector 而不是 C 风格的固定长度数组。
  • 总是,总是检查文件是否成功打开。这显然不是你的情况。最可能的原因是程序在与您放置文件的位置不同的地方寻找 input.txt。

标签: c++ arrays file visual-c++


【解决方案1】:

你的程序是正确的。工作正常。

目前,它没有获取文件。所以,它对你来说是失败的。

提供 readFile() 的完全限定路径,如下例:

Path like "C:\\Users\\source\\Temp\\x64\\Debug\\input.txt"

Windows 支持带反斜杠或正斜杠的文件路径:

msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-10
    • 1970-01-01
    • 1970-01-01
    • 2012-11-08
    • 2018-03-18
    • 1970-01-01
    • 1970-01-01
    • 2011-05-21
    相关资源
    最近更新 更多