2016-01-15 60 views
-6

這可能是一個簡單的問題,但我不明白我的代碼有什麼問題。我只是想讓程序讀取一個字符並將它從二進制文件返回到程序中。我不明白爲什麼它不接受變量。這裏有一些代碼:無法返回ifstream數據? C++

int ncharf() 
{ 
    int neww; 
    myfile.get(neww); 
    return neww; 
} 

我檢查了類似的問題,但他們沒有幫助。我錯過了什麼嗎?

這裏的錯誤:

Severity Code Description Project File Line Suppression State Error C2228 left of '.get' must have class/struct/union

而且,它沒有之前這樣做,但現在它說myfile是無效的標識符。

我能得到它的唯一方法是用「int」替換「neww」,但是我不能返回值!

int main() 
{ 
    return 0; //To stop unwanted execution 
    char curchar[100000000]; 
    ifstream myfile; 
    myfile.open("befen.bin", ios::in, ios::binary); 
    ofstream yourfile("enn.bin", ios::out); 
    int i = 1; 
    if (myfile.is_open()) 
    { 
     int evar; 
     while (!myfile.eof()) 
     { 
      int snchar[100000000]; 
      snchar[i] = ncharf(); 
      evar = rand() % 5 + 1; 
      if (evar = 1) 
      { 
       snchar[i] = (snchar[i] + 10); 
      } 
      if (evar = 2) 
      { 
       snchar[i] = (snchar[i] + 40); 
      } 
      if (evar = 3) 
      { 
       snchar[i] = (snchar[i] * 56); 
      } 
      if (evar = 4) 
      { 
       snchar[i] = (snchar[i]/3); 
      } 
      yourfile << snchar[i]; 
      yourfile << evar; 
      i = i + 1; 
     } 
    } 
    else 
    { 
     cout << "There was an error opening the file"; 
    } 
    return 0; 
} 

我添加了主要功能。我將如何結合你所說的@barmar?

回答

1

你忘了通過myfile作爲參數。

int ncharf(istream &myfile) 
{ 
    char neww; 
    myfile.get(neww); 
    return (int)neww; 
} 

此外,作爲@Barmar評論:The argument to .get() must be of type char, not int

如果你想讀一個二進制文件一個int,你應該使用istream::read代替:

​​
+0

有一種可能性,即'myfile'是一個全局變量,不需要通過。 –

+0

@ThomasMatthews看看OP得到的錯誤消息。它抱怨'.get'沒有被應用於類對象。 – Barmar

+0

如果我想以二進制模式讀取文件中的int,我需要在get方法中指定int *的大小,否則它將讀取單個字符。例如:'myfile.get((char *)&new,sizeof(int))'。 –