无法停止读取 c++ 中的行

Can't stop reading lines in c++

本文关键字:c++ 读取 无法停止      更新时间:2023-10-16

以下代码适用于 10 月 17 日到期的家庭作业。问题指出"编写一个带有循环的程序,允许用户输入一系列数字。输入所有数字后,程序应显示输入的最大和最小数字。

#include "stdafx.h"
#include <algorithm>
#include <array>
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
using namespace std; 
bool isNumeric(string aString)
{
    double n; 
    istringstream is; 
    cin >> aString;
    is.str(aString);
    is >> n;
    if (is.fail()) 
    {
        return false;
    }
    return true; 
}
vector<double> limits(vector<double> a)
{
    // Returns [min, max] of an array of numbers; has
    // to be done using std::vectors since functions 
    // cannot return arrays. 
    vector<double> res; 
    double mn = a[0]; 
    double mx = a[0]; 
    for (unsigned int i = 0; i < a.size(); ++i)
    {
        if (mn > a[i])
        {
            mn = a[i]; 
        }
        if (mx < a[i])
        {
            mx = a[i]; 
        }
    }
    res.push_back(mn); 
    res.push_back(mx); 
    return res; 
}
int main()
{
    string line = " "; 
    vector<string> lines; 
    vector<double> arr; 
    cout << "Enter your numbers: " << endl; 
    while (!line.empty() && isNumeric(line))
    {
        getline(cin >> ws, line); 
        if (line.empty() || !isNumeric(line))
        {
            break;
        }
        lines.push_back(line);
        transform(line.begin(), line.end(), line.begin(), [](char32_t ch) {
            return (ch == ' ' ? '00' : ch); 
        }); // Remove all spaces 
        arr.push_back(atof(line.c_str())); 
    }
    vector<double> l = limits(arr); 
    cout << "nMinimum: " << l[0] << "nMaximum: " << l[1] << endl; 
    return 0; 
}

上面的代码是我所拥有的。但是,它并不总是输出正确的最大值,并且仅输出"0"作为最小值。我似乎找不到这有什么问题,所以如果有人能帮忙,那就太好了。

至少,您的问题似乎在于在 limits() 函数中将 min 的值初始化为 0。因此,如果你有一个 [1, 2, 3, 4] 的数组,它将检查每个元素,并看到它们都不小于 0,将 0 作为最小值。若要解决此问题,可以将初始值 mn 设置为数组的第一个元素。请注意,您必须检查以确保数组至少有一个元素,以避免可能的溢出错误。

对于最大值,我不确定您有什么样的不一致,但是如果您的数组仅包含负值,则会遇到与最小值相同的问题,其中初始值高于任何实际值。