从cin中分配变量的有效方法

时间:2017-05-01 03:19:45

标签: c++ c++11 cin

所以在过去我不得不接受一行输入,其中不同的数字或字母用空格分隔(例如" 1100 2 100 1")并为其分配每组数字或字母& #39;各自的变量。 例如,如果用户输入" 1100 2 100 1"该程序需要添加第一行数字" 1100"到一个名为' string1'," 2"的字符串数组;到一个名为' num'," 100"到一个名为' string2'等的字符串数组。

我一直处理这个问题的方法是使用一系列for循环,if语句和计数器来记住我们在cin输入中的位置:

// 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];
    }
}
}

正如你所看到的那样,这是一个非常丑陋和漫长的过程,所以如果有人能够向我展示一种更好的方式来分割输入并将其存储在未来,那将非常感激。谢谢!

1 个答案:

答案 0 :(得分:0)

像这样使用git myclone

stringstream