2013-03-20 78 views
3

我有從該被格式化這樣讀文件到對象陣列C++

ABCD(字符串)1(INT)2(INT)3(INT)
ABCDE(字符串)4的數據文件讀取( int)3(int)2(int)


我想執行一些函數,只使用同一行中的變量。但這是我的代碼。我是初學者,所以請糾正我的謝謝。

在實現文件

#include "Vehicle.h" 
#include iostream> 
#include fstream> 
#include string> 
#include cstdlib> 
#include cmath> 

using namespace std; 


void Vehicle::readFile(string filename) 
{ 
    ifstream myIn; 

int totalNum=0; 

myIn.open(filename.c_str()); 
if (!myIn) 
{ 
    cerr<<"Data file failed to open!\n"; 
    exit (0); 
} 
for (int i=0; i<MAX; i++) 
{ 
    while (myIn.peek() != EOF) 
    { 
     myIn>>calc[i].name; 
     myIn>>calc[i].a; 
     myIn>>calc[i].b; 
     myIn>>calc[i].c; 

     totalNum++; 
    } 
} 
myIN.close(); 

,然後我想顯示什麼,我只是從

for (int i = 0; i < MAX; i++) 
cout << calc[i].name << calc[i].a << calc[i].b << calc[i].c << endl; 

對不起,我離開了文件讀取.h文件

#include <string> 
using namespace std; 


#ifndef CALC_H 
#define CALC_H 


class Calc 
{ 
public: 

    void readFile(string file); 

private: 

    string name; 
    int a; 
    int b; 
    int c; 
}; 

#endif 

如果我走在正確的道路上,我只想知道很多東西。謝謝

+0

不妨使用'while(myIn >> calc [i] .name >> calc [i] .a >> calc [i] .b >> calc [i] .c){ totalNum ++;}' – chris 2013-03-20 20:50:56

回答

2

正確的做法是將您的類Calc>>運算符超載。

class Calc { 
    public: 
     friend istream& operator >>(istream& myIn, Calc& calc); 
}; 

istream& operator >>(istream& myIn, Calc& calc) { 
    myIn >> calc.name; 
    myIn >> calc.a; 
    myIn >> calc.b; 
    myIn >> calc.c; 

    return myIn;  
} 

現在,你可以這樣做:

while (myIn >> calc[i]) { 
    ++totalNum; 
} 
+0

嗯,這有點危險,因爲它可能會在中間流失,但我不知道這是否可以接受和/或如何改善它。 – 2013-03-20 20:56:59

+0

@AlexChamberlain顯然,OP將不得不說明這一點...這只是一個基本的I/O提示。 – Tushar 2013-03-20 20:57:57

+0

謝謝。對不起,我甚至不能投票。但這是否與對象數組一起工作?我可以只添加一個循環,並從第一行讀取,如calc [i] .name然後calc [i] .a? – 2013-03-20 20:59:14

0

你應該考慮不同的設計有點。

創建一個類,它包含一行,即字符串int int int - 就像你在「Calc」中所做的那樣,但不依賴於你如何創建一行(readfile)。讓我們把它叫做「線」

class Line 
{ 
public: 
    std::string name; 
    int a; 
    int b; 
    int c; 
}; 

現在,因爲你需要讀幾行,你會需要某種容器來保存它們,創建行向量(或其他容器)

std::vector<Line> contents; 

然後按照Tushar的建議覆蓋流操作符,所以當你從一個文件讀取(或者從例如stdin)時,你可以爲你讀的每一行創建Line實例,這些實例用來填充'contents'數組。可以開始做任何你想要做的事情實際操作calc

+0

或者我可以在客戶端主界面創建一個循環。cc,只讀一行並執行一些功能,然後重複?你會怎麼做? – 2013-03-21 01:41:10

+0

有很多方法可以處理這個問題,你可以像你說的那樣做,而不需要存儲任何東西,只需要在讀入時進行計算。 – 2013-03-21 05:08:31