0

The task is to read an integer array from a user and then count sort it. I used vector to take input of the array but it only stops reading integers after I enter non-integer symbol when it has to do it after the last integer. For example, if I enter (5 4 3 2 1) it does not proceed further but keeps expecting input from a user. Also the sorted array must look like "1 2 3 4 5) but I have 0 at the beginning of it (0 1 2 3 4 5).

#include <iostream>
#include <string>
#include <cstring>
#include <vector>

using namespace std;

int main(){
    vector<int> arr;
    int x;
    int j = 0;
    while(cin.good()==1){
        cin>>x;
        arr.push_back(x);
        j++;
    }
    cin.clear();
    int count_array[j]={0};
    int s=0;
    int new_array[j];
    int i;
    for(i=0; i<j; i++)
        count_array[arr[i]]++;
    for(i=0; i<j; i++){
        count_array[i] = count_array[i] + s;
        s=count_array[i];
    }
    for(i=0;i<j;i++){
        new_array[count_array[arr[i]]]=arr[i];
        count_array[arr[i]]--;
    }

    for(i=1;i<=j;i++)
    {
        cout<<new_array[i]<<" ";               
    }
    return 0;
}
lemeow
  • 21
  • 2
  • 1
    You will be surprised to learn that `cin.good()` is still true after reading the last number, so an extra number, a garbage number gets read. And that's what you're counting. – Sam Varshavchik Oct 25 '20 at 15:39
  • ... just a question, but why read the array and sort it afterwards? I would read one entry after the other and add it in the already sorted list. – Dominique Oct 25 '20 at 16:01
  • You can also use `getline` to read the entire line as a `string`, then parse them into separate numbers as needed, so you don't need to input an arbitrary input afterwards. – Ranoiaetep Oct 25 '20 at 16:05
  • Also note [variable-length arrays is not standard C++](https://stackoverflow.com/questions/1887097/why-arent-variable-length-arrays-part-of-the-c-standard) – Ranoiaetep Oct 25 '20 at 16:06
  • @Dominique that's the task condition :) – lemeow Oct 25 '20 at 16:18
  • @SamVarshavchik oh now I got it! But how can I get rid of that garbage number? – lemeow Oct 25 '20 at 16:19
  • By fixing the bug, of course. An input stream is no longer any `good()` only after the last I/O operation fails. Reading the last number in the stream does not fail, of course, it succeeds, and the input stream is still `good()`. Now that you understand it, the solution should be obvious to you. – Sam Varshavchik Oct 25 '20 at 16:20
  • @Ranoiaetep Yes, I tried to do read the entire line and then parse it but it was suggested to use the vector method afterwards – lemeow Oct 25 '20 at 16:20
  • I would suggest the same as my previous suggestion would work way slower, and the only benefit is that you don't have to input some arbitrary data on the user side – Ranoiaetep Oct 25 '20 at 16:30

0 Answers0