我在c++应用程序上搞不清楚

I cant figure it out something on a c++ application

本文关键字:程序上 搞不清楚 应用程序 应用 c++ 我在      更新时间:2023-10-16

所以我正在制作一个c++应用程序来解决一些练习。

int i=1;
cout << "How many times :";
cin >> n;
while (n>0)
{
    cout << "Input F" << i << ":";
    if (cin >> a[i] && cin >> sign&& cin>>b)
    {
                switch (sign)
                {
                case'$': a[i] = a[i] * (sqrt(b));
                    break;
                case'^': a[i] = pow(a[i], b);
                    break;
                case'/':a[i] = a[i] / b;
                    break;
                default: cout << "n Wrong sign";
                    break;
                }
    }
    else
        a[i]=a[i];
i++;
n--;
}

在某些情况下,我不需要sing或b变量。。。当我按Enter键时,应用程序不允许我退出if。

例如:我必须输入F1:8sqrt(2),然后输入8$2,然后输入F2:just 8,然后按Enter键,但应用程序一直在询问值。

好的,现在为了让它发挥作用,我需要连续键入两次符号。。。

while (n>0)
{
    cout << "Input F" << i << ":";
    cin >> a[i];
    if (cin.get() == 'n')
        a[i] = a[i];
    else {
        cin >> sign;
        if (sign)
            cin >> b;
        switch (sign)
        {
        case'$':
            a[i] = a[i] * (sqrt(b));
            break;
        case'^': a[i] = pow(a[i], b);
            break;
        case'/':a[i] = a[i] / b;
            break;
        default: cout << "n Wrong sing;
            break;
        }
    }
i++;
n--;
}

谢谢你抽出时间。

你说:

在某些情况下,我不需要sing或b变量。。。当我按Enter键时,应用程序不允许我退出if。

这是因为程序正在等待您输入所需的所有值

if (cin >> a[i] && cin >> sign&& cin>>b)

您可以通过输入所有必要的输入或输入EOF(输入EOF是特定于平台的)来摆脱该语句。

通过逐行读取输入并使用std::istringstream独立处理每一行,您会过得更好。

while (n>0)
{
   std::string line;
   cout << "Input F" << i << ":";
   if ( ! getline(cin, line) )
   {
      // Error reading the next line.
      break;
   }
   // Now extract the data from the line using a istringstream.
   std::istringstream str(line);
   if (str >> a[i] && str >> sign && str >> b)
   {
      switch (sign)
      {
         case'$': a[i] = a[i] * (sqrt(b));
                  break;
         case'^': a[i] = pow(a[i], b);
                  break;
         case'/': a[i] = a[i] / b;
                  break;
         default: cout << "n Wrong sign";
                  break;
       }
    }
    else
       a[i]=a[i];
    i++;
    n--;
}