首页 > 解决方案 > C++'没有重载函数的实例'为什么我会收到这个错误?

问题描述

#include<iostream>
#include<cmath>

using namespace std;


int main()

{ 
    string name, choice;
    int age;

    cout << "Enter a name: ";
    //Getline will allow to take an entire line as an input and not a char 
   getline(cin, name);
   cout << "Enter choice of meal: ";
   getline(cin, choice);
   cout << "Enter age: ";
   **getline(cin, age);**

   cout << "My name is " << name << endl;



  return 0;

}

这是我的代码问题在粗线中,谁能告诉我为什么会出现错误以及解决方案?

标签: c++getline

解决方案


您编码不起作用的答案是getline()在线允许您读取字符串而不是整数。有趣的是,C++ IOStreams 库中没有提供读取其他类型的工具。这很有趣,因为基于行和基于分隔符的流处理,尤其是混合它们,总是问题的根源。我想说,能够使用您尝试过的方法会更容易、更安全。

有一个简单的解决方案(未经测试):

template<typename value_type>
istream&
getline(std::istream& in, value_type& val)
{
    std::string line;
    if (!getline(in, line)) {
        return in;
    }
    std::istringstream iss(line);
    if (!(iss >> val)) {
        in.setf(std::ios::failbit);
    }
    return in;
}

基本上,它读取一行,然后分两步将其转换为相应的目标类型。


推荐阅读