【问题标题】:Efficient way of assigning variables from cin从cin分配变量的有效方法
【发布时间】:2017-05-01 03:19:44
【问题描述】:

因此,在过去,我不得不接受由空格分隔的不同数字或字母的单行输入(例如 "1100 2 100 1" ),并将每组数字或字母分配给它自己的相应变量。 例如,如果用户输入“1100 2 100 1”,程序需要将第一行数字“1100”添加到名为“string1”的字符串数组中,将“2”添加到名为“num”的 int 中,将“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];
    }
}
}

如您所见,这是一个非常丑陋且冗长的过程,因此,如果有人能向我展示一种更好的方法来拆分输入并在将来存储它们,我们将不胜感激。谢谢!

【问题讨论】:

  • std::cin &gt;&gt; string1 &gt;&gt; num &gt;&gt; string2 有什么问题?
  • 我从来没有真正使用过 '>>' 运算符,所以我将我的解决方案归结为缺乏经验。

标签: c++ c++11 cin


【解决方案1】:

像这样使用stringstream

std::string input;
std::getline(std::cin,input);
std::stringstream inputStream(input);
// get any type, later
inputStream >> var1 >> var2 ...

【讨论】:

  • 哇哦,太棒了。感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 2011-01-10
  • 2017-12-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-10
相关资源
最近更新 更多