samedi 4 juillet 2020

Extract integer from string and form an array

Starting out C++ in my school and it is looking so much more daunting than Python! Hopefully someone can guide me on this.

I have created a simple user I/O to practice on extracting integer from the user input and forming an array based on the inputs. See below:

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

int main() {

    int number_array = {};
    string user_input;

    cout << "Enter your array range: ";
    cin >> user_input;
    cout << "You have entered: " + user_input << endl;

    return 0;
}

When entering the input, the user need to adhere to this format

x-y or x - y (e.g 0-5 or 0 - 5)

I have this in my mind which I believe will work but I can't translate it into C++.

  1. Program will extract the first and last integer from user input, '-' will be remove. I am thinking that regex can do the trick but not too sure how to code it in.
  2. Based on the first and last integer, it will form an integer array in number_array. For example, 0-5 will form [0, 1, 2, 3, 4, 5] and -4--1 will form [-4, -3, -2, -1]. I assume a for loop will need to be use here.

Aucun commentaire:

Enregistrer un commentaire