无法读取.txt文件

时间:2016-10-20 05:03:56

标签: c++ text-files fstream

我的代码如下:

string file_name;
int weight;
int distance;
char slash = '/';
string line = "";

ifstream myfile(file_name);

cout << "Enter the path of the file you want to read from. \n";
cin >> file_name;
ifstream inFile (file_name);
inFile.open(file_name.c_str());
if (inFile.is_open())
{
    while (getline (inFile,line) )
    {
        inFile >> setw(7) >> weight >> setw(7) >> distance;
        cout << "\n" << setw(4) << weight << setw(4) << distance;
    }
    inFile.close();
}
else cout << "Unable to open file";

我试图浏览用户输入路径的文件的每一行。我使用的文件有数百行数据,我想遍历每一行并分隔每个元素(每行有相同的元素集)然后移动到下一行并做同样的事情。然而,没有任何东西被提取出来,也没有任何东西被提取出来。有没有人有任何想法,为什么这不能按预期运作?

1 个答案:

答案 0 :(得分:0)

向你走X-Y。这是C ++,所以让我们尝试一些面向对象,不管吗?

我没有使用许多不同的数据和复杂的解析规则,而是建议对数据强加顺序并使用顺序来简化解析。

我只展示日期,但其他信息也可以根据您的需求和逻辑建议收集到类和结构中。

#include <sstream>
#include <iostream>

using namespace std;

// a simple date structure. Could be a class, but this is C++. structs ARE classes.
struct Date
{
    string  year;
    string  month;
    string  day;

};

// make a input stream reader for Date
istream & operator>>(istream & in, Date & date)
{
    getline(in, date.year,'/'); // grab everything up to the first /
    getline(in, date.month,'/'); // grab from first / to the second /
    getline(in, date.day, ' '); // grab from second / to first space
    return in;
}

// make a output stream writer for Date
ostream & operator<<(ostream & out, const Date & date)
{
    return out << date.year << '/' << date.month << '/' << date.day;
}
int main()
{
    string file_name;
    string line;

    // using a preloaded string stream instead of file. Easier to debug.
    stringstream inFile("2016/3/16 2016/3/23 f 581 3980 3 n n 15 Ken Jones x232@gmail.com\n2016/5/28 2016/11/3 s 248 17 3 n y 20 Katy Perry kperr@gmail.com\n2016/2/13 2016/8/8 w 79 1123 2 n y 21 Betty White bwhite@gmail.com\n2016/2/22 2016/4/14 f 641 162 2 n n 22 Earl Grey earlgrey@gmail.com");
    while (getline(inFile, line)) // read a line
    {
        stringstream linestream(line); // put line into another stream
        Date est; // allocate a couplte Dates
        Date mv;
        linestream >> est >> mv; // read into Dates

        cout << "\n"
             << est.year << '/' << est.month << '/' << est.day << " " // print hard way
             << mv; // print easy way
    }
}

示例输出:

2016/3/16 2016/3/23
2016/5/28 2016/11/3
2016/2/13 2016/8/8
2016/2/22 2016/4/14