Reading a list of numbers and sorting C++

arrays, c++, sorting

Solution

The line causing the error is:

numbers = cout << std::setw(10) << n;

I'm not quite sure what you're trying to do here, it looks like you just want to print it in which case the `numbers =` isn't needed.

The structure of your loop to read all the data is problematic also. The line: `while (!inputFile.eof())` isn't idiomatic C++ and won't do what you hope. See here for a discussion on that issue (and here).

For reference you can do this quite simply with less work by using `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;
}

This program also uses a `std::vector` instead of an array to abstract the "how big should my array be?" problem (which your example looked to have a possible problem problem with).

Problem

I'm trying to read a list of numbers from a file and sort them by reading them into an array and then sorting the contents of the array. But I'm getting ``` error:incompatible types in assignment of 'std::basic_ostream<char, std::char_traits<char> >' to 'int [1]' ``` I'm fairly new to programming and this is my first time working with C++ Can anyone tell me how to write the list of numbers to an array so that I can sort them? Here is what I have: ``` #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; } ```

Original source

Related problems