显示向量 (C++) 时出现运行时错误



我在 c++ 中显示向量时遇到问题,我的语法似乎与我看到的示例相匹配,但程序崩溃并在控制台中给出 11db 消息。我正在创建一个程序,该程序要求输入和单位类型,然后存储它们,并根据输入的数据提供各种示例统计信息,程序中的断点专门在线:

for(int i=0;i<totalMeters.size();i++) 

整个程序都在这里,我已经成功地运行了它,除了矢量打印之外的所有功能。

#include <iostream>
#include<cmath>
#include<string>
#include<vector>
using namespace std;
double number1=100000;
double number2=-100000;
double howClose;
double newnum;
double sum=0;
double numberOfValues=0;
string unit;
string number1Unit;
string number2Unit;
double waitingNum;
vector <double> totalMeters;
void unitizer()
{
    while(cin>>newnum)
    {
        cout<<"what is the unit?(cm,m,in,ft)"<<endl;
        cin>>unit;
        if(unit!="ft"&&unit!="m"&&unit!="in"&&unit!="cm")
        {
            cout<<"incorect input"<<endl;
            unitizer();
        }
        cout<<newnum<<endl;
        if(newnum<number1)
        {
            number1=newnum;
            number1Unit=unit;
        }
        if(newnum>number2)
        {
            number2=newnum;
            number2Unit=unit;
        }
        sum+=newnum;
        numberOfValues++;
        cout<<"the smallest value so far is "<<number1<<number1Unit<<".";
        cout<<"the largest value so far is "<<number2<<number2Unit<<".";


        if(number1==number2)
        {
            cout<<number1<<number1Unit<<" is equal to "<<number2<<number2Unit<<endl;
        }
        if (unit=="cm")
            waitingNum=newnum/100;
        if (unit=="in")
            waitingNum=newnum*.0254;
        if (unit=="ft")
            waitingNum=newnum*.3048;
        if (unit=="m")
            waitingNum=newnum;
        totalMeters.push_back(waitingNum);

        howClose=abs(number1-number2);
        cout<<"The difference between the two values is "<<howClose<<"."<<endl;
        if(howClose<.001)
            cout<<"Wow, that's close"<<endl;
        cout<<"input one number please.(enter a non number to end the program.)"<<endl;
    }
}
void finalResults()
{
    cout<<"The sum of all the values is "<<sum<<"."<<endl;
    cout<<"the number of values enters is "<<numberOfValues<<"."<<endl;

}

void vectorOutput()
{
    for(int i=0;i<totalMeters.size();i++)
    {
        cout<<totalMeters[i]<<endl;
    }

}
int main(int argc, const char * argv[]) {
    cout<<"input one number please."<<endl;
    unitizer();
    finalResults();
    vectorOutput();
    return 0;
}

附言我试图查看正在调用的实际函数,但发现它很长,超出了我目前对语言的理解。

const char * argv[] 这不是标准C++。您不应该使用全局变量并使用更好的名称或注释,因为如果不费吹灰之力就很难理解您的逻辑。- 尼尔柯克

简单地取出额外的增强似乎可以解决问题

最新更新