У меня есть вопрос в этом коде. Что получает функция, когда мы используем 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;
}