我有一个非常简单的程序,我正在启动,但当我试图运行它时,它得到"有一个初始人口",然后每次崩溃。作为上下文,我在windows 10上使用visual studio 2015。
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
/*Ideas for features to add
*----------------------------
*Trade, agriculture, traffic, tourism, housing, crime rate, language, religion
*/
string version = "1.0";
void main() {
cout << "Welcome to Population Simulator v" + version + ".n";
cout << "In this game we will simulate a city and how the population numbers change over time.n";
//City initialization
cout << "Please input a name for your city: ";
string name;
cin >> name;
cout << "Please input an initial population of the city (Recommended: 10,000): ";
int population = 0;
cin >> population;
int initialPopulation = population;
int initialWealth = population * 10000;
int wealth = initialWealth;
int year = 2000;
cout << name + " has an initial population of ";
cout << population + " and an initial net-worth of $" + wealth;
cout << ".n";
}
int weather() {
return 0;
}
int NPG() { //natural population growth
return 0;
}
表达式:
population + " and an initial net-worth of $" + wealth
并不像你想象的那样。它在指向" and an initial net-worth of $"
的char指针上执行算术,导致一个无效指针,当程序试图使用它打印时导致崩溃。
试题:
cout << population << " and an initial net-worth of $" << wealth;