while循环退出时,Visual C ++简单程序崩溃 [英] visual c++ simple program crashes when while loop exits

查看:93
本文介绍了while循环退出时,Visual C ++简单程序崩溃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

bool quit = false;
	int totalValue = 0;
	char userChoice = 'a';


	// as long as user hasn't selected quit, the statements will execute
	while (!quit){

		//initialize the array
		int myArray[3];

		// ask user to enter the values of each array element
		for  (int i = 0; i<4; i++){
			cout << "enter the integer value for element number " << i << endl;
			cin >> myArray[i];
		}
	
		// sum up all the element values and display them
		for(int i=0;i<4; i++){
			totalValue += myArray[i];
		}

		cout << "The sum of all the values is " << totalValue << endl;

		// ask user if they would like to continue or quit
		cout << "would you like to continue (y or n)" <<  endl;
		cin >> userChoice;

		if(userChoice == 'n'){
			quit = true;
		}


	}
	cout << "program exiting";



大家好.上面程序的问题是,当用户输入n退出程序时,它会崩溃.它也暗示了主循环中的前几条语句是原因,因为然后我将它们注释掉,使循环工作正常.如您所知,我对c ++还是陌生的,因此希望这很容易.谢谢.



Hi guys. The problem with the above program is that it crashes when the user enter n to exit the program. It also seams that the first few statements in the main loop are the cause because then I comment them out the loop works fine. As you can tell I am new to c++ so this should hopefully be an easy one. Thanks.

推荐答案

问题可能是(尽管它看上去对您而言不大):

The problem is probably (though it doesn''t look likt it to you):

int myArray[3];

// ask user to enter the values of each array element
for  (int i = 0; i<4; i++){
    cout << "enter the integer value for element number " << i << endl;
    cin >> myArray[i];
}


您声明一个包含3个整数的数组,并使用4:myArray [0],myArray [1],myArray [2]和myArray [3].由于它在堆栈上,因此很有可能会炸毁您的程序!


You declare an array with 3 integers, and use 4: myArray[0], myArray[1], myArray[2], and myArray[3]. Since this is on the stack, it is quite possible that this will blow your program!


而不是quit=true;,请使用break;


这篇关于while循环退出时,Visual C ++简单程序崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆