读取数字列表并排序C++

Jmh*_*013 3 c++ arrays sorting

我正在尝试从文件中读取数字列表,并通过将它们读入数组然后对数组内容进行排序来对它们进行排序.但我得到了

error:incompatible types in assignment of 'std::basic_ostream<char, std::char_traits<char> >' to 'int [1]' 
Run Code Online (Sandbox Code Playgroud)

我对编程很新,这是我第一次使用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;
}
Run Code Online (Sandbox Code Playgroud)

Fle*_*exo 6

导致错误的行是:

numbers = cout << std::setw(10) << n;
Run Code Online (Sandbox Code Playgroud)

我不太确定你在这里要做什么,看起来你只想打印它,在这种情况下numbers =不需要.

用于读取所有数据的循环结构也存在问题.这一行:while (!inputFile.eof())不是惯用的C++,不会做你想要的.请参阅此处以了解该问题(以及此处).

作为参考,您可以通过使用较少的工作来完成此操作 std::sort

#include <iterator>
#include <algorithm>
#include <vector>
#include <fstream>
#include <iostream>

int main() {
  std::ifstream in("test.txt");
  // Skip checking it

  std::vector<int> numbers;

  // Read all the ints from in:
  std::copy(std::istream_iterator<int>(in), std::istream_iterator<int>(),
            std::back_inserter(numbers));

  // Sort the vector:
  std::sort(numbers.begin(), numbers.end());

  // Print the vector with tab separators: 
  std::copy(numbers.begin(), numbers.end(), 
            std::ostream_iterator<int>(std::cout, "\t"));
  std::cout << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

这个程序还使用一个std::vector数组而不是一个数组来抽象"我的数组应该有多大?" 问题(你的例子看起来可能存在问题).