c++ - cin 作为函数参数
问题描述
我在这段代码中有一个问题。当我们使用 cin 作为参数时,函数会收到什么。例如,当 cin 找到空格或 '\n' 时停止,所以如果输入是“1 2 3 4 5”,程序将返回 5,但我不明白为什么。
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
double max_value(istream& in) // can be called with 'infile' or 'cin'
{
double highest;
double next;
if (in >> next)
highest = next;
else
return 0;
while (in >> next)
{
if (next > highest)
highest = next;
}
return highest;
}
int main()
{
double max;
string input; cout << "Do you want to read from a file? (y/n) ";
cin >> input;
if (input == "y")
{
string filename;
cout << "Please enter the data file name: ";
cin >> filename;
ifstream infile; infile.open(filename);
if (infile.fail())
{
cerr << "Error opening " << filename << "\n";
return 1;
}
max = max_value(infile);
infile.close();
}
else
{
cout << "Insert the numbers. End with CTRL-Z." << endl; max = max_value(cin);
}
cout << "The maximum value is " << max << "\n";
return 0;
}
解决方案
推荐阅读
- android - 使用 JNI 从 C++ 异步调用 Kotlin 函数
- git-flow - gitflow-shFlags:Git 中没有这样的文件或目录
- authentication - 使用发布在 Java 中的授权令牌从 Google 获取刷新令牌
- android - 片段不再附加到活动
- java - 在 Spring Boot 应用程序的生产环境中禁用 GraphiQL Playground
- api - 如何在 Next.js 的 api 函数中获取 css 样式 url
- c# - 在页面加载时调用异步方法并等待完成执行 - c#
- python - 如何将一个csv表分成多个或如何分隔表中的行并使用python将该表放入邮件正文?
- jenkins - 如何通过编写 jenkins 声明性管道将 jenkins 构建保存到工作区中
- php - Laravel 8 调用未定义的方法 Illuminate\Database\MySqlConnection::tabel()