gpt4 book ai didi

c++ - sublime text C++ 编译导致段错误

转载 作者:行者123 更新时间:2023-11-28 02:17:41 25 4
gpt4 key购买 nike

我最近从 windows 上的 dev c++ 切换到 osx 开发环境,并尝试使用 sublime text 3。但是,当我运行我的程序时,出现段错误。这是错误消息:

/bin/bash: line 1: 20506 Segmentation fault: 11  "/Users/jimi/Documents/University/lab0603"
[Finished in 1.2s with exit code 139]
[shell_cmd: g++ "/Users/jimi/Documents/University/lab0603.cpp" -o "/Users/jimi/Documents/University/lab0603" && "/Users/jimi/Documents/University/lab0603"]
[dir: /Users/jimi/Documents/University]
[path: /usr/bin:/bin:/usr/sbin:/sbin]

完整代码如下:

#include <iostream>
#include <cmath>

using namespace std;


string flightDirections[16] = {"ENE", "NE", "NNE", "N", "NNW", "NW", "WNW", "W", "WSW", "SW", "SWS", "S", "SSE", "SE", "ESE", "E"};
double cruisingSpeed = 0;
double windSpeed = 0;
int windDirection = 0;
double flightDistance = 0;

string numberToDirection(int direction) {

return (direction) ? "The wind is blowing from the East." : " The wind is blowing from the West.";

//this way we only have one return statement :)

}

void getInput () {
cout << "Hello! \n"
<< "Thank you for choosing to use this really great program!! \n"
<< "This program will compute the necessary heading adjustment for your flight,"
<< " and provide the estimated flight time. \n";
cout << "Enter the aircraft cruising speed in still air (in km/h): ";
cin >> cruisingSpeed;
cout << " \n \t cruising speed = " << cruisingSpeed << "\n Enter the wind speed in km/h: ";
cin >> windSpeed;
cout << " \n \t wind speed = " << windSpeed << "\n Enter 1 if the wind is blowing from the West and -1 if wind is blowing from the East:";
cin >> windDirection;
cout << "\n\t" << numberToDirection(windDirection) << "\n Enter the distance between the originating and destination cities, in km:";
cin >> flightDistance;
cout << "\n\t flight distance = " << flightDistance << "\n Enter the compass direction of the destination city, relative to the originating cities, using the following values:";
for (int i = 0; i < sizeof(flightDirections); i++) {
cout << i + 1;
cout << flightDirections[i];
}
cin.ignore();


}

int main() {


getInput();
return 0;

}

这是怎么回事?

最佳答案

您的问题出在您的 for 循环上。

for (int i = 0; i < sizeof(flightDirections); i++) 

由于 sizeof(flightDirections) 大于数组的大小,因此将超出数组的末尾。 sizeof(flightDirections)sizeof(std::string) * number_of_elements_in_the_array。为了获得正确大小的数组,您需要使用

sizeof(flightDirections) / sizeof(flightDirections[0])

或者更好的是使用 ranged based for loop作为

int i = 0;
for (const auto & e : flightDirections) {
cout << ++i << e;
}

关于c++ - sublime text C++ 编译导致段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33552795/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com