繁体   English   中英

混合 cin >> 和 getline() - C++

[英]Mixing cin >> and getline() - C++

有人告诉我,除非超出必要,否则我应该只在我的代码中使用两者之一,cin 或 getline。

Cin 我被告知会产生异常错误等(不检查输入类型等)

我知道 getline() 对字符串和字符更加灵活,但是数字类型呢? 我的意思是,我可以将 getline 字符串解析为数值,但是没有更安全的路线吗? 问题是,对于字符串和数字输入,我应该采用哪种方法?

int inputReturn(int x);

int defaultValue = 0;

int main()
{

  //Getting numerical input w/getline()
  string input = "";

  while(true)
   {
    cout << "Enter a value: ";
    getline(cin, input);

    stringstream myStream(input);
    system("CLS");

    if(myStream >> defaultValue)
      {
        system("CLS");
        break;
      }
    cout << "Invalid input. Try again!" << endl << endl;

   }

    inputReturn(input); //Converted to numeric value, but still type of string (Error)
    system("CLS");

return 0;
}

int inputReturn(int x)
{
  return x*2;
}

在这个例子中,我将字符串输入解析为一个数值,然后将该值用作 int 的参数,并得到一个 string 到 int 的错误。

那么,问题 - 我应该为这些数据类型使用什么,还是可以同时使用两者?

希望大家理解我的提问。

getline()可以用于数值,但不能用于整数或双精度。 在你的情况下,可以使用。

还记得#include <string>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM