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

时间:2017-10-15 01:59:44

标签: c++

以下代码适用于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 == ' ' ? '\000' : 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”作为最小值。我似乎无法找到这个有什么问题,所以如果有人能提供帮助那就太好了。

1 个答案:

答案 0 :(得分:0)

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

最大限度地,我不确定您遇到了什么样的不一致,但如果您的数组只包含负值,那么您将遇到与最小值相同的问题,其中初始值更高比任何实际值都要多。