2013-04-17 58 views
-1

我有下面的代码填充数组并打印出数组,然后以相反的顺序打印数组。我的问题是现在我已经完成了,我怎样才能代替从循环填充列表,而不是从文件填充它?从文件读取到数组

代码:

void popArray(int array1[]){ 
    for(int x = 0; x < 10; x++){ 
    array1[x] = x; 
    cout << setw(2) << array1[x]; 
    } 
} 

void reverseList(int array1[]){ 
    for(int x = 9; x > -1; x--){ 
    cout << setw(2) << array1[x]; 
    } 
} 


int main() 
{ 
    int array1[9]; 

    popArray(array1); 

    cout << "\n"; 

    reverseList(array1); 
} 
+2

什么是文件格式?顺便说一下,您正在访问数组的边界之外。我想你想要一个大小为10的数组,所以它应该是'int array1 [10];'。 –

+3

查找'std :: ifstream'有大量的例子和文档。 –

+0

是文件二进制还是一次只读一行,将字符串转换为整数然后将其存储到数组中? –

回答

0

这取决于你是如何计划让数字在您的文件。 你可以在一行上各有一个整数,并继续读取文件直到结束,或者你可以有csv值。 然后,您可以读取popArray函数中的文件。 下面是在读一本文件中的一些参考: http://www.cplusplus.com/doc/tutorial/files/

如果您计划在该文件中的每一行使用一个整数,下面是你可以使用。

void popArray(int array1[], std::string filename) { 
    ifstream myfile (filename); 
    while (myfile.good()) 
    { 
     std::string line; 

     getline (myfile,line); 
     array1[x] = atoi(line.c_str()); 
     cout << line << endl; 
    } 
    myfile.close(); 
}