c++ - 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;
}
这是我的代码问题在粗线中,谁能告诉我为什么会出现错误以及解决方案?
解决方案
您编码不起作用的答案是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;
}
基本上,它读取一行,然后分两步将其转换为相应的目标类型。
推荐阅读
- react-native - 更改屏幕时没有出现 ActivityIndicator
- r - R:如何查找/替换然后自动执行代码?
- python - 如何将字典附加到字典?
- python - 如何在.cfg文件中存储带有#的单词
- c# - Azure Web App - 大文件上传、单个 POST 请求与每个文件的多个帖子
- c# - Mac 上的 Visual Studio 进入调试模式,没有断点,对 ASP.NET Core 有不寻常的建议
- flutter - 如何在执行某些功能之前延迟 1 秒?
- angular - Angular 8:未定义文档中的错误:Entrypoint = index.html
- machine-learning - 连接没有输出的 Keras 模型
- ios - 如何将 UICollectionViews 放入 stackView?