dimanche 30 avril 2017

Efficient way of assigning variables from cin

So in the past I have had to take in a single line of input with different numbers or letters separated by spaces ( e.g. "1100 2 100 1" ) and assign each set of numbers or letters to it's own respective variable. For example, if user enters "1100 2 100 1" the program needs to add the first line of numbers "1100" to a string array called 'string1', "2" to an int called 'num', "100" to a string array called 'string2', etc..

The way I have always handled this problem is with a series of for-loops, if-statements and counters to remember where in the cin input we are up to:

// Takes in an input from the user and adds them to the required strings and chars to be used in main.

void addToList()
{
std::string temp;

std::getline( std::cin, temp );

// Takes each element from cin and stores them in variables accordingly.
int length = temp.length();

int i;
int j;
int k;
int l;

// Adds the first set of numbers from cin into the string array 'binarystr1'
for ( i = 0; i < length; i++ )
{
    if ( temp[i] == ' ' )
    {
        break;
    }

    if ( temp[i] >= 0 )
    {
        binarystr1 += temp[i];
    }

}

int bs1Length = binarystr1.length();

// Sets the char 'k1' to the second number in cin.
for ( j = bs1Length+1; j < length; j++ )
{

    if ( temp[j] == ' ' )
    {
        break;
    }

    if ( temp[j] >= 0 )
    {
        k1 = temp[j];
    }

}

int newLength = bs1Length + 3;

// Adds the 3rd line of numbers entered in cin to the string 'binarystr2'.
for ( k = newLength; k < length; k++ )
{
    if ( temp[k] == ' ' )
    {
        break;
    }
    if ( temp[k] >= 0 )
    {
        binarystr2 += temp[k];
    }
}

int bs2Length = binarystr2.length();
int lastLength = newLength + bs2Length+1;

// Sets char 'k2' to the last number entered in cin.
for ( l = lastLength; l < length; l++ )
{
    if ( temp[l] == ' ' )
    {
        break;
    }
    if ( temp[l] >= 0 )
    {
        k2 = temp[l];
    }
}
}

As you can see this is a very ugly and lengthy process, so if someone could show me a better way of splitting up input and storing them in the future, it would be greatly appreciated. Thanks!

Aucun commentaire:

Enregistrer un commentaire