我正在尝试从文件中读取一组数字,并通过将它们读入数组并对数组内容进行排序来对它们进行排序。但我遇到了问题。
error:incompatible types in assignment of 'std::basic_ostream<char, std::char_traits<char> >' to 'int [1]'
我是一名新手程序员,这是我第一次使用C++。请问有谁能告诉我如何将数字列表写入数组,以便我可以对它们进行排序?以下是我的代码:
#include <fstream>
#include <iostream>
#include <iomanip>
#define ANYSIZE_ARRAY 1
using std::cout;
using std::endl;
int main()
{
const char* filename = "test.txt";
std::ifstream inputFile(filename);
int numbers[ANYSIZE_ARRAY];
int i, key;
// Make sure the file exists
if(!inputFile)
{
cout << endl << "The File is corrupt or does not exist. " << filename;
return 1;
}
long n = 0;
while(!inputFile.eof())
{
inputFile >> n;
numbers = cout << std::setw(10) << n;
}
for(int j=1;j<5;j++)
{
i=j-1;
key=numbers[j];
while(i>=0 && numbers[i]>key)
{
numbers[i+1]=numbers[i];
i--;
}
numbers[i+1]=key;
}
//Display sorted array
cout<<endl<<"Sorted Array\t";
for(i=0;i<5;i++)
cout<<numbers[i]<<"\t";
cout<<endl;
}
numbers
太小了,无法读取你试图读入的行数。错误消息中的int[1]
让我们知道,在最后的for
循环中,你试图从一个只有 1 个值的数组中输出 5 个值,这是有问题的。在对其进行排序之前,打印未排序的数组可能会很有价值。最终,你将想要使用标准的sort
模板函数。也许可以使用int
向量来动态分配条目。 - Jonathan Leffler