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

标签 c++ cin getline

有人告诉我,除非必要,否则我应该只在代码中使用cin或getline这两个代码中的任何一个。

有人告诉我会产生异常错误,例如(不检查输入类型等)

我知道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的参数,并得到int的字符串错误。

因此,问题-这些数据类型应使用什么?

我希望你们能理解我的询问。

最佳答案

getline()可以用于数值,但不能用于整数或 double 。
在您的情况下,可以使用。

还记得#include <string>

关于c++ - 混合cin >>和getline()-C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33145266/

相关文章:

c++ - 将 CUDA 添加到 ROS 包

c++ - C++ 代码的意外输出

c++ - getline(param1,param2,param3) 在 C++、linux 中的用法

c++ - 为什么 cin 工作而 cin.getline 不工作?

c++ - Cin 跳过输入整数

c++ - getline 函数不工作

c++ - 需要一些帮助来澄清我试图完成 C++ 的一段代码

C++ 等于运算符

c++ - 在函数调用中获取函数的要求

c++ - 将值输入到结构