-2

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

代码:

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);
}
4

1 回答 1

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();
}
于 2013-04-17T14:41:52.330 回答