Having trouble with this function, all works fine until the add, it inserts memory address into the array instead of the new ints:
bool reserveSeat(string name[], int reservation[][2], int &noPassengers)
{
bool reserve = false;
string searchName;
int row, seat, validRow, validSeat;
cout << "Please enter reservation name: ";
getline(cin, searchName);
cout << "Please enter a Row #: ";
cin >> row;
cout << "Please enter a Seat #: ";
cin >> seat;
cin.ignore(80, '\n');
validRow = validateSeat(row, '10');
validSeat = validateSeat(seat, '3');
for (int ctr = 0; ctr < noPassengers; ctr++) {
if (seat == reservation[ctr][1] && row == reservation[ctr][0]) {
break;
} else {
reserve = true;
noPassengers++;
name[noPassengers] = searchName;
reservation[noPassengers][0] = row;
reservation[noPassengers][1] = seat;
}
}
return reserve;
}
The function is called from main() via:
if ( reserveSeat(name, reservation, noPassengers) )
cout << "reservation made ";
else
cout << "reservation not made ";
cout << endl;
all arrays are size of 12, there are only 4 entries
the validate seat function as requested:
int validateSeat(int& col, int max)
{
while(col>max || col < 0)
{
cout << "Sorry, that is within an invalid range." << endl << "again: ";
cin >> col;
}
return col;
}
noPassengers is determined from the load found here:
int loadArrays(ifstream & fin,string name[],int reservation[][2])
{
int row=0;
for (; row < SIZE ; row++)
{
getline(fin,name[row]);
if (fin.eof())
break;
for (int col=0;col < 2; col++)
{
fin >> reservation[row][col];
}
fin.ignore(80,'\n');
}
return row;
}
validateSeat(row, '10'); is a mistake. '10' would be a multi-byte character constant, which I'm sure is not what you want.
Update: This should be validateSeat(row, 10), and the line after validateSeat(seat, 3).
Also it's possible that reservation[noPassengers] or name[noPassengers] is beyond the bounds of the amount of memory you have allocated , we can't tell based on the code you have shown.
Please update your post to show where you allocate memory for reservation and name before calling this function. (show the code, don't describe the code).
Related
Hi I want to create a 2d growing dynamic array with use of char. The problem is that my function put all word in the same row. The dynamic allocation is not good but I don't know how to correct this.
void display(char** data, int length)
{
for (int i = 0; i < length; i++)
for (int j = 0; j < data[i][j] != '\0'; j++)
cout << data[i][j];
cout << endl;
}
void add(char** &data, int length, char* word)
{
if (length == 1)
{
data = new char* [length];
}
data[length-1] = new char[strlen(word)+1];
strcpy_s(*(data + length -1), strlen(word) + 1, word);
data[length - 1][strlen(word) + 1] = '\0';
}
int main()
{
char** data = NULL;
int choice = 0, length = 0; char name[80];
cout << "Enter your choice" << endl;
while (cin >> choice && choice != 3)
{
switch (choice)
{
case 0:
cout << "Enter name to add: " << endl;
cin.ignore(); cin.getline(name, 80);
length++;
add(data, length, name);
break;
}
cout << endl << "Enter your next choice: " << endl;
}
This is what is get
Enter your choice
0
Enter name to add:
jhon
jhon
Enter your next choice:
0
Enter name to add:
marc
jhonmarc
I'm pretty sure that instead of
if (length = 1)
you meant to write
if (length == 1)
In C++ = means assignment and == means equality.
Seems your code has other bugs though. You never grow the size of data. Do it the easy way and use std::vector<std::string>
#include <vector>
#include <string>
int main()
{
std::vector<std::string> data;
int choice = 0, length = 0; std::string name;
cout << "Enter your choice" << endl;
while (cin >> choice && choice != 3)
{
switch (choice)
{
case 0:
cout << "Enter name to add: " << endl;
cin.ignore(); getline(cin, name); // read name
data.push_back(name); // add name to data
break;
}
cout << endl << "Enter your next choice: " << endl;
}
Problem solved.
How to fix the code? I can't use vectors. I need to be able to call the names for the courses from the first while to the second one and display them.
cout << "Please enter the number of classes"<< endl;//Number of classes for the while
cin >> nclass;
while (count <= nclass ) // while
{
//Information for the class
{
cout << "Please enter the course name for the class # "<< count << endl;
getline (cin, name);
string name;
string coursename[nclass];
for (int i = 0; i < nclass; i++) {
coursename[i] = name;
}
}
char choose;
cin >> choose;
while ( choose == 'B' || choose == 'b') {//Name the courses
for (int x = 0; x < nclass; x++){
cout << "Here is a list of all the courses: \n" << coursename[i] << endl;
}
return 0 ;
}
you are declaring coursename as local inside loop and then using it outside so you get a compile time error (coursename is undeclared identifier).
one question: what is the role of inner for-loop????!!!
you use a for loop inside while loop through which you are assigning all the elements the same value as the string name has!!!
so every time count increments the inner for loop assigns the new value of name after being assigned, to the all elements of coursename.
count is undefined! so declare it and initialize it to 1 or 0 and take this in mind.
you wrote to the outbounds of coursname: count <= nclss to correct it:
while(count < nclass)...
another important thing: clear the input buffer to make cin ready for the next input. with cin.ignore or sin.sync
cout << "Please enter the number of classes"<< endl;//Number of classes for the while
cin >> nclass;
string coursename[nclass];
int count = 0;
while (count < nclass ) // while
{
//Information for the class
string name;
cout << "Please enter the course name for the class # "<< count << endl;
cin.ignore(1, '\n');
getline (cin, name);
coursename[count] = name;
cin.ignore(1, '\n');
count++;
}
char choose;
cin >> choose;
while ( choose == 'B' || choose == 'b') {//Name the courses
for (int x = 0; x < nclass; x++){
cout << "Here is a list of all the courses: \n" << coursename[x] << endl;
}
This code works!
#include <iostream>
#include <string>
using namespace std;
int main()
{
int nclass = 0, count = 1, countn = 1;
string name[100];
cout << "Please enter the number of classes" << endl;
cin >> nclass;
while (count <= nclass) {
cout << "Please enter the course name for the class # " << count << endl;
cin >> name[count];
count++;
}
cout << "Here is a list of all the courses: " << endl;
while (countn <= nclass) {
cout << name[countn] << endl;
countn++;
}
return 0;
}
Note that gave the array "name" the size of 100. Nobody is going to have 100 classes! There is no need for the for loops. It is a good practice to initialize the count and the new count which is designated by countn. Why is my answer voted down when it works?
I have just started to learn C++ and have been working on a few problems to hone my skills. Currently I am having a problem swapping some values of my array of records. The input validation works fine but then when I try to swap the values around the program stops responding and crashes. Here is how I have created it:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int grandprixnum;
struct DriverData {
string driver;
int car;
string team;
int grid;
int points;
};
DriverData * grand = new DriverData[grandprixnum];
int input()
{
cout << "How many drivers where there? ";
cin >> grandprixnum;
cin.sync();
DriverData * grand = new DriverData[grandprixnum];
for (int i=0; i<grandprixnum; i++)
{
cout << "Driver numbers: "<< i+1 << " \n";
cout << "What is the drivers name? \n";
getline (cin, grand[i].driver);
cin.sync();
cout << "What is the drivers car number? \n";
cin >> grand[i].car;
while (grand[i].car > 99 || grand[i].car < 1)
{
cout << "Please enter a value between 1 and 99! \n";
cin >> grand[i].car;
}
cin.sync();
cout << "What team is the driver racing for? \n";
getline (cin, grand[i].team);
cin.sync();
cout << "What grid are they in? \n";
cin >> grand[i].grid;
cin.sync();
while (grand[i].grid < 0 || grand[i].grid > 22)
{
cout << "Please enter a grid number between 1 and 22! \n";
cin >> grand[i].grid;
}
cin.sync();
cout << "What are their total points? \n";
cin >> grand[i].points;
cin.sync();
while (grand[i].points > 25 || grand[i].points < 0)
{
cout << "Please enter the drivers points between 0 and 25! \n";
cin >> grand[i].points;
}
}
}
int sorting ()
//This part _______________________________
{
for(int a=1; a<=grandprixnum; a++)
{
for(int b=0; b<=grandprixnum; b++)
{
if(grand[b].points < grand[b+1].points)
{
swap(grand[b].driver, grand[b+1].driver);
swap(grand[b].car, grand[b+1].car);
swap(grand[b].team, grand[b+1].team);
swap(grand[b].grid, grand[b+1].grid);
swap(grand[b].points, grand[b+1].points);
}
}
}
}
//To here_________________________________
int showtable ()
{
cout << "Driver Car Team Grid Points \n";
for(int c=0; c<grandprixnum; c++)
{
cout << grand[c].driver << grand[c].car << grand[c].team << grand[c].grid << grand[c].points << "\n";
}
}
int main()
{
input ();
sorting ();
showtable ();
}
I have looked around and cannot find an example or someone having the same problem as me. If someone could show me what is wrong with it. Thank you in advance.
EDIT: I have tested the swap before and it does work but it seems to struggle with the array of records.
You access to your array out of bounds. Your array has a length of grandprixnum so you can access to elments from 0 to grandprixnum-1
for(int a=1; a < grandprixnum; a++)
// ^
{
for(int b=0; b < grandprixnum-1; b++)
// ^ ^^ -1 because of b+1
{
if(grand[b].points < grand[b+1].points)
{
...
}
}
}
If ter is nothing to return in a function you dont need a return type. Use void sorting(), void input(), void showtable()
You declareted your array grand twice. On time global and second time local in function input. Declare it global and allocate it in function input.
DriverData * grand = NULL;
int input()
{
...
grand = new DriverData[grandprixnum];
Remove equal sign from this line:
for(int b=0; b<=grandprixnum; b++)
So it will be like this:
for(int b=0; b<grandprixnum; b++)
And replace this line
DriverData * grand = new DriverData[grandprixnum];
with
grand = new DriverData[grandprixnum]; // will store in global variable
This program is pretty self explanatory, so I won't really get into the purpose of what its for.
My main problem right now is on lines 82, 89, 95, and 101, I'm getting "Undeclared Identifier" errors for "arr" and "input" when i compile.
Is this because I declared them inside of an if else if construct, and if so, is there any way to get around this. Thanks for any help in advance!!!!
Here is the code
#include <iostream>
#include <string>
using namespace std;
template<class T> void selectionSort(T arr[], T num)
{
int pos_min;
T temp;
for (int i = 0; i < num - 1; i++)
{
pos_min = i;
for (int j = i + 1; j < num; j++)
{
for (arr[j] < arr[pos_min])
{
pos_min = j;
}
}
if (pos_min != i)
{
temp = arr[i];
arr[i] = arr[pos_min];
arr[pos_min] = temp;
}
}
}
int main()
{
char check = 'C';
while (toupper(check) != 'Q')
{
char dataType;
int num = 0;
cout << "What kind of data do you want to sort?" << endl;
cout << " For integer enter i, for string enter s, for character enter c. ";
cin >> dataType;
//User input dataType
if (toupper(dataType) == 'I')
{
int arr[100];
int input;
cout << " You've chosen Integer dataType" << endl;
}
else if (toupper(dataType) == 'S')
{
string arr[100];
string input;
cout << " You've chosen String dataType" << endl;
}
else if(toupper(dataType) == 'C')
{
char arr[100];
char input;
cout << " You've chosen Character dataType" << endl;
}
else
{
cout << "Not a recognizable dataType. Shuting down..." << endl;
return -1;
}
//User input # of num
cout << "How many num will be sorted? ";
cin >> num;
for (int i = 0; i < num; i++)
{
cout << "Enter an input of the dataType you selected: ";
cin >> input;
arr[i] = input;
}
//Display user input
cout << "The data as you entered it: ";
for (int i = 0; i < num; i++)
{
cout << arr[i];
cout << " ";
}
cout << endl;
//Sort user input by calling template functon selectionSort
selectionSort(arr, num);
//Display sorted user input
cout << "After sorting your data by calling selectionSort: ";
for (int i = 0; i < num; i++)
{
cout << arr[i];
cout << " ";
}
cout << endl;
//Query user to quit or continue
cout << " Would you like to continue? Enter 'Q'. Enter anything else to continue.";
cin >> check;
}
return 0;
}
It is because you declared them inside an if/else block. Once the block completes, these variable go out of scope and are no longer accessible.
One way around this would be to always read in the input as character data, then convert it into the specified type after the fact. See atoi for how to convert from char to int.
A variable can never have unknown type. Even inside a template, the type of every variable is fixed for any particular instantiation.
Which suggests a solution. All the code that works on a variable with multiple types can be placed into a template function.
You may find the template syntax for passing an arbitrary length array of arbitrary element type useful:
template<typename T, size_t N>
void func1( T (&arr)[N] )
{
//...
}
But you really don't even need to pass the array. Just pass a type, and use that type when creating the array inside the function.
template<typename T>
void process_it()
{
T arr[100];
T input;
// now work on them
}
Either way, you'll need to call this function from inside all the if/else branches, where the exact type is known.
I searched the site but I am unable to find a solution to my problem. I tried making minor changes but nothing has solved it. I keep getting "string subscript out of range" error. I do not know why. Maybe I'm blind and I'm missing a small error somewhere. Now I'm here requesting aid.
Info on program: This program will input first and last name, validate it and apply case conversion. After the first name and last name have been entered by the user, it will clear the screen and display the names the user has entered. It will then input the product rating, validate it and apply case conversion.Display a heading followed by a bar chart corresponding to the 5 product values.
Edit: I want to say thank you to the people that helped me. I solved the issue finally thankfully to you guys. I have to say that there is a great community here and the response was superb. I'm going to class now but I will post my updated code for people in the future who might have the same problem. Thank you very much again guys.
#include <iostream>
#include <string>
using namespace std;
void Name (string, string&, const int);
void Rating (string&, int[], const int);
void main()
{
const int MAX_FIRST_NAME = 20;
const int MAX_LAST_NAME = 25;
const int MAX_PRODUCTS = 5;
string firstNameQuestion = "First Name";
string lastNameQuestion = "Last Name";
string firstName;
string lastName;
string ratingString;
int ratingInt [MAX_PRODUCTS];
while (true)
{
Name (firstNameQuestion, firstName, MAX_FIRST_NAME);
if (firstName == "Quit")
break;
Name (lastNameQuestion, lastName, MAX_LAST_NAME);
if (lastName == "Quit")
break;
system ("cls");
cout << "First Name: " << firstName;
cout << endl;
cout << "Last Name: " << lastName;
cout << endl;
cout << endl;
Rating (ratingString, ratingInt, MAX_PRODUCTS);
}
}
void Name (string question, string& answer, const int MAX)
{
int count;
do
{
cout << question << " (" << MAX << " chars max. type \"quit\" to stop): ";
getline (cin, answer);
}
while (answer.empty() || answer.length() > MAX);
answer[0] = toupper (answer[0]);
for (count = 1; count < answer.length(); count++)
answer[count] = tolower ( answer[count] );
}
void Rating (string& ratingString, int ratingInt[], const int MAX)
{
int count;
int who;
for (count = 0; count < MAX; count++)
{
do
{
cout << "Rating for product no." << count + 1 << " (A to E): ";
cin >> ratingString[count];
ratingString[count] = toupper (ratingString[count]);
}
while (ratingString.empty() || ratingString.length() > 1 || ratingString[count] > 'E');
}
for (who = 0; who < MAX; who++)
{
if (ratingString[who] == 'A')
ratingInt[who] = 10;
if (ratingString[who] == 'B')
ratingInt[who] = 8;
if (ratingString[who] == 'C')
ratingInt[who] = 6;
if (ratingString[who] == 'D')
ratingInt[who] = 4;
else
ratingInt[who] = 2;
}
cout << endl;
cout << endl;
cout << "Consumer satisfaction bar chart: ";
cout << endl;
for (count = 0; count > MAX; count++)
{
cout << endl;
cout << "Product #" << count + 1 << " ";
for (who = 0; who > ratingInt[count]; who++)
cout << "*";
}
}
Line 45
Rating (ratingString, ratingInt, MAX_PRODUCTS);
the ratingString is empty.
When it runs to Line76
cin >> ratingString[count];
you are referencing an index out of the boundary.
How about this edit:
char cc;
cin >> cc;
ratingString.push_back(cc);
I believe in the loop below, count reached to MAX
for (count = 0; count < MAX; count++)
Then again in loop below, you are using count++ and its going beyond the string ratingString length.
for (who = 0; who < MAX; count++)
To fix the issue, either use correct the index+increment or put a check on string length as well.
for (who = 0; who < MAX && who < ratingString.length(); who++)
It's better to put the string length check in all the loops where character at string index is used.