2014-11-08 235 views
-4
#include <iostream> 
#include <stdlib.h> 
#include <string> 
#include <fstream> 

struct specific {int distance; int arrive_time; int depart_time;}; 
int maxn=100; 
ifstream File("c:\\data.txt"); 
if (!File.is_open()) 
{ 
cout << "Unable to open file!"; 
exit(-1); 
} 
else 
{ 
int l; 
string rows; 
while (getline(File,rows)){ 
++l;} 
int data[l]; 

if (l>maxn) 
{ 
cout << "Too much data!"; 
File.close(); 
exit(-1); 
} 
else 
{ 
int i=1; 
while (!File.eof() && i<=l) 
{ 
Filel >> data[i]; 
i++; 
} 

if (i!=l) 
{ 
cout << "Inconsitent File!"; 
File.close(); 
exit(-1); 
} 
} 
}; 
Fajl.close(); 

n = l/3; 
specific station[n]; 
int j=1; 
do{ 
for (int i=; i<=l; i+=3){ 
data[i] == station[j].distance; 
data[i+1] == station[j].arrive_time; 
data[i+2] == station[j].depart_time; 
j++;}} 
while (j<=n); 
} 

我是全新的C++和編程。我的目標是 - 部分地打開給定的文本文件,其中包含數字,每行一個數字(除此之外)。我需要將這些最終讀入到名爲station [n]的數組中。爲此,我在File和目標(站)數組之間放置了一個int數組。 station數組是一個結構體,我不允許改變它。目標是將文本文件中的數字讀入數據數組,然後將它們從那裏放入數組中。如何從文本文件讀取int數組,在c + +中?

訣竅是,電臺陣列有3個品質的每個元素:例如station [1]必須有距離,arri_time和depart_time(所有正整數)。這也意味着站點的數量將等於文本文件中的行數除以3.

我懷疑這可能是在沒有數據數組的情況下完成的,但即使如此,我的代碼仍然停留在一開始:它根本無法正確讀取文件。我讀過這個論壇上的一些文章,以及其他人,沒有幫助...... 上面的代碼只是一個部分,請考慮任何未聲明的元素,相應地在我的主代碼中聲明。

感謝您的幫助!

+2

請縮進代碼。第二:'int data [l];'不是合法的C++,因爲'l'是一個變量。如果您正在學習C++,請關閉編譯器給您的擴展,並在沒有它們的情況下學習語言。 – PaulMcKenzie 2014-11-08 19:11:17

+0

爲什麼你不格式化你的代碼? – 2014-11-08 23:15:42

回答

0

2014年C++不害怕使用標準庫和載體:

#include <fstream> 
#include <vector> 

int main() 
{ 
    std::vector<int> data; 
    std::ifstream DataFile("c:\\data.txt"); 

    if (DataFile) 
    { 
     int value; 
     // read the elements 
     while (DataFile >> value) 
     { 
      data.push_back(value); 
     } 
    } 
    return 0; 
} 
+0

此代碼不起作用。 – 2016-10-14 18:40:32