程序在输入要放入向量"|"后崩溃。[基本]

  • 本文关键字:崩溃 基本 向量 程序 c++
  • 更新时间 :
  • 英文 :


这个程序在老师显示的输出上正确运行,但如果我输入1 2 3 4 5 6,它就不起作用|或任何数字。

#include "std_lib_facilities.h"
int main()
{
cout << "Enter a series of double values, which represent the distance between two citiesn"
"(followed by '|' or a another non double/integer character):n";
vector<double> distances; // city distances
for (double distance; cin >> distance; ) // read into distance
distances.push_back(distance);  // put distance into vector

// compute total distance:
double sum {0.0};
for (double distance : distances)
sum += distance;
cout << "Total distance: " << sum << 'n';
// compute smallest and largest distance:
sort(distances); // sort distances
cout << "Smallest distance: " << distances[0] << 'n'
<< "Largest distance: " << distances[distances.size()-1] << 'n';


cout << "The mean distance between two cities is: " << sum/distances.size() << 'n';
keep_window_open();
return 0;
}

我将您的代码转换为某种东西"更标准";。

请参阅:

#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
std::cout << "Enter a series of double values, which represent the distance between two citiesn"
"(followed by '|' or a another non double/integer character):n";
std::vector<double> distances; // city distances
for (double distance; std::cin >> distance; ) // read into distance
distances.push_back(distance);  // put distance into vector

// compute total distance:
double sum{ 0.0 };
for (double distance : distances)
sum += distance;
std::cout << "Total distance: " << sum << 'n';
// compute smallest and largest distance:
std::ranges::sort(distances); // sort distances
std::cout << "Smallest distance: " << distances[0] << 'n'
<< "Largest distance: " << distances[distances.size() - 1] << 'n';

std::cout << "The mean distance between two cities is: " << sum / distances.size() << 'n';
return 0;
}

它按预期工作。但是它需要C++20以及为函数使用正确的名称空间限定符。

总是需要使用一些不重要的东西,比如#include "std_lib_facilities.h"。请始终使用限定名称,而不是using namespace . . .