我已经写了下面的代码来读取文件(area.inp)中列中的数据到数组。当在屏幕上显示数据时,第一个“for”循环显示正确的数字(所以代码正确读取文件中的数字),但第二个“for”循环显示不正确的数字组。我无法解决问题。我将不胜感激关于这个问题的任何指导。将文件中的数据存储到数组中
area.inp
001.000 003.000
002.000 004.000
006.000 005.000
004.000 002.000
002.000 001.000
代码
#include <iostream>
#include <iomanip>
#include <fstream>
#include <algorithm>
#include <iterator>
using namespace std;
int main(int argc, char **argv)
{
int j=0;
double X[j];
double Y[j];
static double *p;
double *q;
p=X;
q=Y;
//**** Counting the number of lines
ifstream myfile("area.inp");
myfile.unsetf(ios_base::skipws);
int points = count(
istream_iterator<char>(myfile),
istream_iterator<char>(),
'\n');
cout << "Number of data in file: " << points << "\n";
//**** Open data file and result
cout <<"file is open"<< endl;
ifstream infile;
infile.open("area.inp", ios::in);
cout <<"Reading data from file"<< endl;
for (j=0; j<points; j++)
{
cout << std::setprecision(3) << std::fixed;;
infile >> X[j] >> Y[j];
cout << "Value of X["<<j<<"]: " << X[j] << endl;
cout << "Value of Y["<<j<<"]: " << Y[j] << endl;
}
cout <<"Showing numbers stored in array"<< endl;
for (j=0; j<points; j++)
{
cout << "Value of X["<<j<<"]: " << X[j] << endl;
cout << "Value of Y["<<j<<"]: " << Y[j] << endl;
}
infile.close();
return 0;
}
Number of data in file: 5
file is open
Reading data from file
Value of X[0]: 1.000
Value of Y[0]: 3.000
Value of X[1]: 2.000
Value of Y[1]: 4.000
Value of X[2]: 6.000
Value of Y[2]: 5.000
Value of X[3]: 4.000
Value of Y[3]: 2.000
Value of X[4]: 2.000
Value of Y[4]: 2.000
Showing numbers stored in array
Value of X[0]: 5.000
Value of Y[0]: 3.000
Value of X[1]: 2.000
Value of Y[1]: 4.000
Value of X[2]: 4.000
Value of Y[2]: 5.000
Value of X[3]: 4.000
Value of Y[3]: 2.000
Value of X[4]: 2.000
Value of Y[4]: 2.000
------------------
(program exited with code: 0)
Press return to continue
看看'INT J = 0;双X [j];'。 X可以存储多少个元素? – NathanOliver
除了'double X [j];'不是标准的C++时'j'不是一个常量表达式的事实。 – crashmstr