Lukas Guldstøv
Lukas Guldstøv

Reputation: 101

std::cin string to int array with variable length input

I have a task where i need to revert a list of variable length numbers. This could be "1 2 3" or "5 6 7 8 9 10". The sorting itself works fine. But I can't figure out how to read the user input (with variable length) and then only execute the reverseSort once. How can I read the user input into an array where each index is based on the space between the numbers?

Here is my code:

#include <iostream>
#include <string>
 
using namespace std;

bool sorted = true;
int temp;
int * arr;
int arrLength = 5;
int arrs;

// int arr = {1,2,3,4,5};

void reverseSort(int arr[], int n){
    sorted = true;

    for (int i = 0; i < n-1; i++){
        if (arr[(i + 1)] > arr[i]){
            temp = arr[i];
            arr[i] = arr[i+1];
            arr[i+1] = temp;
            sorted = false;
        } 
    }

    if (!sorted){
        reverseSort(arr,n);
    } 

}

 int main(void){

     // get user input !?!?!?!?!
     cin >> arrs;
 
 cout << arrs;
    reverseSort(arr,arrLength);
    for (int i = 0; i < arrLength; i++){
        std::cout << arr[i] << " ";
    } 
    return 0;
}

Upvotes: 0

Views: 612

Answers (1)

If you don't know number of inputs you need struct that can be resized. std::vector is good for it. For adding new data you can use member function push_back.
You can read the input line as std::string (by std::getline) and you can open new stream with read data (std::istringstream). Further one can read values from new stream.
And I think you can use std::sort instead of reverseSort (but for 'reverse' you need use std::greater as comparator).

#include <vector>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <algorithm>

int main(void){
    
    std::vector<int> arrs;
    
    // read only one line
    std::string input;
    std::getline(std::cin, input);
    std::istringstream row(input);
    int x;
    while (row >> x)
    {
        arrs.push_back(x);
    }
    
    //like your reverseSort
    std::sort(arrs.begin(), arrs.end(), std::greater<int>{});
    
    for (auto var : arrs) {
        std::cout << var << "; ";
    }
    
    return 0;
}

Upvotes: 1

Related Questions