簡體   English   中英

無法讀取.txt文件

[英]Trouble reading a .txt file

我的代碼如下:

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";

我試圖遍歷用戶輸入路徑的文件的每一行。 我正在使用的文件包含數百行數據,我想遍歷每一行並分隔每個元素(每行具有相同的元素集),然后移至下一行並執行相同的操作。 什么都沒有被提取,什么也沒有被引用。 是否有人對為什么它無法按預期運行有任何想法?

對您進行XY處理。 這是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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM