2016-11-11 894 views
-2

我正在爲學校的C++項目工作,其中程序將從文本文件中讀取數字列表,將它們存儲在一個動態數組中,然後將它們打印到另一個文本文件中。說實話,我有點迷失在這個指針,我得到的錯誤「一個類型的值」void「不能用於初始化我的主源文件中的」int「類型的實體。C++動態數組:無法使用「void」類型的值來初始化類型爲「int」的實體

Main.cpp的(這是我得到的錯誤):

#include "dynamic.h" 

int main 
{ 
    readDynamicData("input.txt","output.txt"); 
} 

dynamic.cpp(骨架的程序):

#include "dynamic.h" 


void readDynamicData(string input, string output) 
{ 
    DynamicArray da; //struct in the header file 
    da.count = 0; 
    da.size = 5; //initial array size of 5 

    int *temp = da.theArray; 
    da.theArray = new int[da.size]; 


    ifstream in(input); 
    ofstream out(output); 

    in >> da.number; //prime read 
    while (!in.fail()) 
    { 
     if (da.count < da.size) 
     { 
      da.theArray[da.count] = da.number; 
      da.count++; 
      in >> da.number; //reprime 
     } 
     else grow; //if there are more numbers than the array size, grow the array 
    } 


    out << "Size: " << da.size << endl; 
    out << "Count: " << da.count << endl; 
    out << "Data:" << endl; 
    for (int i = 0; i < da.size; i++) 
     out << da.theArray[i]; 

    in.close(); 
    out.close(); 

    delete[] temp; 
} 


void grow(DynamicArray &da) //this portion was given to us 
{ 
    int *temp = da.theArray; 
    da.theArray = new int[da.size * 2]; 
    for (int i = 0; i<da.size; i++) 
     da.theArray[i] = temp[i]; 
    delete[] temp; 
    da.size = da.size * 2; 
} 

和dynamic.h中,頭文件:

#include <iostream> 
#include <string> 
#include <fstream> 
#ifndef _DynamicArray_ 
#define _DynamicArray_ 


using namespace std; 

void readDynamicData(string input, string output); 

struct DynamicArray 
{ 
    int *theArray; 
    int count; 
    int size; 
    int number; 
}; 

void grow(DynamicArray &da); 

#endif 
+1

請編輯您的問題以提供[mcve]。 –

+0

我apogolize,但林不知道爲什麼這不符合最小和完整?我不確定爲什麼錯誤被觸發,所以我發佈了整個代碼,因爲它的代碼是在三個文件中的任何一個。請讓我知道如果這不是真的 – pbcrazy

+0

在頭文件中使用名稱空間標準是非常糟糕的東西 – Raindrop7

回答

0

main是一個函數所以它需要括號:

int main(){ 
    // your code 
    return 0; // because it should return intiger 
} 

而且。你的grow也是一個函數,所以如果你想要調用它,你可以寫grow(),它需要DynamicArray作爲參數。

不可能在上編寫工作程序C/C++任何不知道基本語法的編程語言。

+0

顯式'return 0'不是必需的在'main'中,這意味着上面的「因爲它需要......」的評論並不準確。不,它並不是真的需要它。 – AnT

+0

@AnT真。感謝您的糾正。 –

+0

哇,這是一個主要的筆直的錯字,不知道我可能錯過了錯過(),謝謝! – pbcrazy

0

你必須括號添加到主要或任何功能:

int main(){/*your code here ...*/}; 

2-您使用的是未初始化objct:

DynamicArray da; //struct in the header file 
da.count = 0; 
da.size = 5; //initial array size of 5 

所以INT * theArray是一個部件的數據和未初始化,以便歡迎來到段落

da的所有成員都沒有被初始化,所以在使用它之前你必須做。

3-還添加括號成長功能:

else grow(/*some parameter here*/); // grow is a function 

4-在頭文件using namespace std;是一個非常不好的做法。 提示內使用它

5-爲什麼包括iostream和字符串..在包含警戒之前? 將其更正爲:

#ifndef _DynamicArray_ 
#define _DynamicArray_ 

#include <iostream> 
#include <string> 
#include <fstream> 

/*your code here*/ 

#endif 
相關問題