这样的代码:
int _tmain(int argc, _TCHAR* argv[])
{
int *test = new int[];
ifstream f("ofile.txt");
for (int i=0,v; i<10; i++)
{
f>>v;
test[i]=1;
cout<<"\nv = "<<v<<", i = "<<i<<endl;
}
return 0;
}
编译后出现此信息的原因:
我想(如果我错了请纠正我)这是关于内存的一些错误,但我不知道细节。如果我删除其中之一(文件读取或数组)它会起作用。 因此,很高兴听到对问题的解释。
最佳答案
你在想java。要分配这样的数组,您需要给出一个大小。 例如
int *test = new int[20];
然而,更好的方案是使用整数 vector 。
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm> // for sort()
int main(int argc, char *argv[])
{
std::vector<int> data;
std::ifstream fsin("ofile.txt");
int count = 0;
while (fsin.good())
{
int v;
fsin >> v;
if (fsin.good())
{
data.push_back(v);
std::cout << "\nv = " << v << ", i = " << count++ << std::endl;
}
}
std::sort(data.begin(), data.end());
for (size_t i=0; i<data.size(); i++)
std::cout << i << '\t' << data[i] << std::endl;
return 0;
}
关于C++动态数组和文件读取不能一起工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20824890/