Below is my code so far. I am just doing this step by step, for a class assignment. Trying not to give the whole code I just want to know what is wrong with what I have so I can learn to fix it. Thanks for the help.
The goal is to create class driver then to get total lap times, compare them and put them in order of 1st thru 3rd place. I've made this in a simple program already. Now I am trying to make an array of the class driver.
So far this is working, It asks for input correctly, and gives an output but before the end of the program I get:
Debug Error!
Run Time Check Failure #2 - Stack around the variable 'driver' was corrupted.
None of the answers I've found here make sense to my application. I have 0 failures when I run the build before running the program.
I also know not to use single character variables, I just do this as I learn what I'm missing and later change them.
#include <iostream>
#include <string>
using namespace std;
class Driver
{
int carNumber;
public:
void setNumber(int number)
{
carNumber = number;
}
int getNumber()
{
return carNumber;
}
};
int main()
{
int x;
int i;
Driver driver[3];
for (i = 1; i <= 3; i++)
{
cout << "Enter Driver " << i << "'s car number: ";
cin >> x;
driver[i].setNumber(x);
}
for (i = 1; i <= 3; i++)
cout << "driver " << i << "'s number is " << driver[i].getNumber() << endl;
return 0;
}
start for loop as shown below because as we know that array stores n elements from location 0 to n-1.
for (i = 0; i <3; i++)
{
cout << "Enter Driver " << i << "'s car number: ";
cin >> x;
driver[i].setNumber(x);
}
Your array access indexes are wrong.
Arrays start at index 0, not 1, and end at 1 less than the number of elements. So for a declaration of driver[3], the valid indexes are 0, 1, and 2, not 1, 2 and 3. With the wrong indexes, you're writing past the end of the array, causing the stack corruption.
Your write loop should be more like
for (i = 0; i < 3; i++)
{
cout << "Enter Driver " << i << "'s car number: ";
cin >> x;
driver[i].setNumber(x);
}
You'll need to make a similar fix to the read loop.
Related
I am very new to c++ and currently trying to complete a few little challenges to get up to speed with the simpler aspects.
I'm trying to create an array (found info to suggest vectors are the same and better) of structs to hold data about 10 people. Each person has an "index" (to identify person1, person2, person3, etc..), a "num" (to store the collected data) and a "rank" (a variable which I intend to use to sort the people using the data collected)
The code doesn't show any errors before compiling, however, when the first piece of data is entered I get the following message:
"Debug Assertion Failed!
Program: C:\WINDOWS\SYSTEM32\MSVCP140D.dll
File: d:\program files\microsoft visual studio\community\vc\tools\msvc\14.12.25827\include\vector
Line: 1795
Expression: vector subscript out of range"
I have tried searching through multiple threads but I can't seem to work out why this problem is occurring.
My code:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
struct person
{
int index; /*person number*/
int num; /*number of pancakes eaten*/
int rank; /*rank used for sorting people*/
};
vector<person> people; /*create a vector (array) of "person"'s*/
void getData()
{
cout << "You will be asked to enter data from 10 different people" << endl;
cout << "\n" << "The question is; 'How many pancakes did they eat for breakfast?'" << endl;
cin.get();
for (int i = 1; i <= 10; i++)
{
system("CLS");
int j;
cout << "Person " << i << " : ";
cin >> j;
person temp;
people.push_back(temp);
people[i].index = i;
people[i].num = j;
people[i].rank = i;
}
}
int main()
{
getData(); /*collect data for the people*/
system("CLS");
cout << "Data Collected : " << endl;
system("pause");
}
Thanks in advance for anyone who can help.
The problem is in your indexing. The index starts at 0 and not 1. So what happens is when you push the first element, it is stored at people[0]. Then you try to access people[1], since i = 1. Hence the subscript is out of range error.
You need to modify the code to be:
....
for (int i = 0; i < 10; i++)
{
system("CLS");
int j;
cout << "Person " << i << " : ";
cin >> j;
person temp;
people.push_back(temp);
people[i].index = i;
people[i].num = j;
people[i].rank = i;
}
....
Current code:
const int MAX_CODENAME = 25;
const int MAX_SPOTS = 5;
struct Team {
string TeamName[MAX_CODENAME];
short int totalLeagueGames;
short int leagueWins;
short int leagueLoses;
};
//GLOBAL VARIABLES:
Team league[MAX_SPOTS];
void addTeams(){
int i = 0; //first loop
int j; //second loop
while(i < MAX_SPOTS){
cout << "****** ADD TEAMS ******" << endl;
cout << "Enter the teams name " << endl;
scanf("%s", league[i].TeamName) ;
}
void searchTeam(){
string decider[MAX_CODENAME];
cout << "Please enter the team name you would like the program to retrieve: " << endl;
cin >> decider[MAX_CODENAME];
for(int i = 0; i < MAX_SPOTS; i++){
if(decider == league[i].TeamName){
cout << endl;
cout << league[i].TeamName << endl;
break;
}else{
cout << "Searching...." << endl;
}
}
}
I really dont know why its not working but I have included all the perquisite header files such as and but the program crashes when i enter the data and then attempt to search. I get the circle of death and then program not responding then says Process returned 255 (0xFF) . It does not even out put Searching.... the program practically gives up as soon as I enter that name.
Also if this can be optimized by the use of pointers that would be great.
tl;dr run-time error causing the search to fail as soon as i type in a name. And for the record I have checked to make sure the name I entered is valid.
scanf doesn't know about std::string. Use std::cin >> league[i].TeamName.
scanf("%s", league[i].TeamName) ;
This should be changed to
std::cin >> league[i].TeamName ;
A couple of other things here....
string decider[MAX_CODENAME];
cout << "Please enter the team name you would like the program to retrieve: " << endl;
cin >> decider[MAX_CODENAME];
Every time you input a value, you are telling the computer to hold the inputted value at decider[25] but the computer only reads indexes 0-24.
if(decider == league[i].TeamName){
Which array slot are you comparing the team name to? If its the 25th element than the statement should be
if(decider[24] == league[i].TeamName){
Pointers are better suited if the number of TeamNames are unknown. Based on the limited code presented, I highly recommend you stay within the realm of basic data types. For the purposes of troubleshooting, please post your full code in the future.
Your TeamName member variable:
string TeamName[MAX_CODENAME];
is an array of 25 strings, so in this line:
scanf("%s", league[i].TeamName) ;
you are courrupting the array. You don't really want an array anyways, so change the TeamName declaration to:
string TeamName;
and then when you read the name, you'll need to use iostreams which knows how to populate a string type (scanf only works with c char arrays):
std::cin >> league[i].TeamName
I am running this code from textbook: An Intro To Design Patterns in C++ with QT.
/* Computes and prints n! for a given n.
Uses several basic elements of C++. */
#include <iostream>
int main() {
using namespace std;
/*
*/
// Declarations of variables
int factArg = 0;
int fact(1);
do {
cout << "Factorial of: ";
cin >> factArg;
if (factArg < 0) {
cout << "No negative values, please!" << endl;
}
}
while (factArg < 0);
int i = 2;
while (i <= factArg) {
fact = fact * i;
i = i + 1;
}
cout << "The Factorial of " << factArg << " is: " << fact << endl;
return 0;
}
The output console only prints one line that says "Factorial is: "
Is that what it's suppose to do?
Yes that is what the program should output at first; it's waiting for you to type a number. If you would step into your code you would soon find out that it will wait for an input on the following line " cin >> factArg;".
So... Go ahead, type a number and press enter :).
Yes you code includes cin >> factArgwhich you will input in the terminal first before the program will run. You may want to put the using namespace std before the main function rather then in it.
I am writing a code to calculate the gross pay of seven employees using arrays. Here is what I have so far
#include <iostream>
#include <iomanip>
using namespace std;
int main ()
{
//Set all constants and variables
const int SIZE = 7; //Size of all arrays
int emID[SIZE] = {1234, 4563, 8765, 4568, 9867, 9235, 7684};
double Hours[SIZE],
Rate[SIZE],
Gross[SIZE];
int index;
Gross[index] = (Hours[index] * Rate[index]);
//Explain Program
cout << "This program calculates an employees gross pay\n";
for (Hours[index];index <= 6; index++)
{
cout << "How many hours did employee " << emID[index] << " work?\n";
cin >> Hours[index];
}
for (Rate[index]; index <= 6; index++)
{
cout << "Enter the pay rate for " << emID[index] << endl;
cin >> Rate[index];
}
for (Gross[index]; index <=6 ; index++)
{
cout << "The gross pay for " << emID[index] << " is " << Hours[index] * Rate[index];
}
}
Unfortunately the program terminates after the first "for" loop. Any suggestions?
There seem to be a few mistakes in your code, which I'm pointing out below.
index is unitialised, and the way you've used it results in Undefined Behavior. I think you meant to initialise to to 0.
You should reset the value of index to 0 between for loops. Currently you would iterate in the first for loop. After that, since index will be > 6, your code will not execute the other two for loops.
Your first term in the for loop declarations is wrong. I think you meant to declare index = 0 there. If not, you should leave it empty.
The line near the beginning where you calculate Gross[index] is wrong and redundant.
I'm new to programming (in general) and C++ (in particular). I'm learning vectors and am trying to write a simple program that:
allows the user to enter a vector of students' test scores
when the user types the sentinel (-1 in this case), the vector terminates
outputs a tally of the student's grades
Here's my code:
#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;
const int SENTINEL = -1;
vector<int> studentGrades = { 0 };
int myInput;
int main()
{
do
{
cout << "Please enter a student's grade: ";
cin >> myInput;
if (myInput < 1000)
{
studentGrades[myInput]++;
}
studentGrades.push_back(myInput);
} while (myInput != SENTINEL);
cout << "\n";
for (int i = 0; i < 1000; i++)
cout << i << " grade(s) of " << studentGrades[i] << endl;
return 0;
}
Two questions:
1) Can anyone provide guidance on why this code is only allowing me to enter one student's grade?
2) Is the for loop that compute the "tally" correct?
Thanks in advance for taking a look,
Ryan
* REVISED CODE *
# JCx - this is the revised code:
#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;
const int SENTINEL = -1;
vector<int> studentGrades = { 0 };
int myInput;
int main()
{
do
{
cout << "Please enter a student's grade (or -1 to QUIT): ";
cin >> myInput;
if (myInput < 1000)
{
studentGrades.at(myInput)++;
}
studentGrades.push_back(myInput);
} while (myInput != SENTINEL);
cout << "\n";
for (int i = 0; i < 1000; i++)
cout << i << " grade(s) of " << studentGrades.at(myInput) << endl;
return 0;
}
and, I'm seeing this error:
Unhandled exception at 0x7707C42D
Microsoft C++ exception: std::out_of_range at memory location 0x0035F890
There's more than one problem. The attempt to access studentGrades[-1] when the users enters your sentinel value, and the fact that the default vector only contains an entry for 0 and the use of push_back.
Let's just walk through some of the problems:
User runs program. User enters 100. studentGrades[100] is out of range. Undefined behaviour occurs as the vector only has one element.
User runs program, enters -1 studentGrades[-1] is out of range.
User runs program, enters 0. studentGrades[0] is in range, incremented to 1. studentGrades.push_back(1) adds an element to the vector studentGrades[1] is now also equal to 1.
As a great starting point, if you swap your subscript vector references for the vector at method as I've shown below you will get out-of-range errors which will help (a lot). The code below still needs work but at least you'll have run-time errors instead of odd behaviour.
int main()
{
do
{
cout << "Please enter a student's grade: ";
cin >> myInput;
if (myInput < 1000)
{
studentGrades.at(myInput)++;
}
studentGrades.push_back(myInput);
} while (myInput != SENTINEL);
cout << "\n";
for (int i = 0; i < 1000; i++)
cout << i << " grade(s) of " << studentGrades.at(myInput) << endl;
return 0;
}
I think if I was implementing this I'd be using std::map instead of a vector. It would let you have a studentGrade[1000] without having to allocate memory for studentGrade[0] to [999] first.
However as you are learning about std::vector check out vector::resize to set the vector big enough for the required elements, std::vector::size to find out whether you need to increase the size. You could then ditch the push_back.
References
vector::at http://www.cplusplus.com/reference/vector/vector/at/
vector::size http://www.cplusplus.com/reference/vector/vector/size/