2016-05-31 22 views
0

該文件讀取AD.txt中的某些數據,將其存儲爲字符串,然後將該字符串寫入ADsubjects.txt。我的寫功能似乎工作正常,但我的閱讀沒有被調用。它甚至沒有進入讀函數來打印cout語句。我認爲,如果我只是簡單地放置呼叫功能,它應該會自動出現。這裏是我的代碼:讀取函數由main調用,但未執行

#include <iostream> 
    #include<fstream> 
    #include <string.h> 
    #include<iomanip> 
    #include <cstdlib> 
    #define rmax 15 
    using namespace std; 
    string data1; 

讀取功能:

void readSubjects(){ 
     cout<<"inside read"<<endl; 
     ifstream is; 
     is.open("AD.txt"); //opening the file 
     cout<<"open text"<<endl; 
     while(!is.eof()){ 
      char line[rmax]; 
      cout<<line<<endl; 
      data1 += "\""; 

      is.getline(line,rmax); 
      for(int i=0; i<11;i++){ 
       data1 += line[i]; 
      } 
      data1 += "\" \\ "; 
     } 
     is.close(); 
    } 

寫功能:

void writeSubjects(){ 
     ofstream os; 
     os.open("ADsubjects.txt",ios::out); 
     os<<data1; 
     os.close() 
    } 

主要功能:

int main() { 
     readSubjects(); 
     cout<<"read"<<endl; 
     writeSubjects(); 
     cout<<"written"<<endl; 
     cout << "Hello, World!" << endl; 
     return 0; 
    } 
+2

不是問題還沒有買,你不應該使用while(!is.eof())' http://stackoverflow.com/questions/5605125/why-is-iostr循環條件考慮錯誤的環境 – NathanOliver

+1

我的猜測是它打印「內部讀取」,但重複的'cout << line << endl;' - 打印未初始化的緩衝區 - 是可能會滾動它的視圖。 – TripeHound

+0

對此進行了擴展,考慮'cout << line << endl;'給出了不確定內容的char緩衝區,並在該語句之前的行中聲明。你的代碼調用*未定義的行爲*。 – WhozCraig

回答

1

在這段代碼;有很多問題。在os.close()

編制問題 - 缺少分號

cout<<line<<endl;代碼後char line[rmax];是錯誤的,因爲它未初始化。打印未初始化的變量可能會弄亂您的終端。

其實readline正確地讀取行。爲什麼使用for循環從行復制11個字符到data1?示例中最大允許長度爲15。你可以把它如下。

data1 += line; 

以下代碼將起作用。

void readSubjects(){ 
     cout<<"inside read"<<endl; 
     ifstream is; 
     is.open("AD.txt"); //opening the file 
     cout<<"open text"<<endl; 
     while(!is.eof()){ 
      char line[rmax]; 
//   cout<<line<<endl; // This is wrong 
      data1 += "\""; 

      is.getline(line,rmax); 

//   for(int i=0; i<11;i++){ 
//    data1 += line[i]; 
//   } 

      data1 += line; 

      data1 += "\" \\ "; 
     } 
     is.close(); 
    } 
0

在爲讀while循環,所有你需要做的是:

while(is){ //the is will run until it hits the end of file. 
     //code here 
    } 

如果readSubjects()不獲取所有調用,那麼也許函數原型需要聲明上面的int main()和實際的函數聲明應該在int main()之下聲明,如下所示:

void readSubjects(); 


    int main(){ 
     readsubjects(); 
     //more code... 
    } 


    void readSubjects() 
    { 
     //actual function code 
    }