I'm a new bie to CPP. I'm trying to use pointer and cin combination which is giving strange result.
int *array;
int numOfElem = 0;
cout << "\nEnter number of elements in array : ";
cin >> numOfElem;
array = new (nothrow)int[numOfElem];
if(array != 0)
{
for(int index = 0; index < numOfElem; index++)
{
cout << "\nEnter " << index << " value";
cin >> *array++;
}
cout << "\n values are : " ;
for(int index = 0; index < numOfElem; index++)
{
cout << *(array+index) << ",";
}
}else
{
cout << "Memory cant be allocated :(";
}
The out put is
What the problem with my code ?
Regards,
Sha
The array++ inside the loop increments the pointer, so by the time you're done with the first loop, array will point outside the originally allocated array.
Just do
cin >> *(array+index);
or simply
cin >> array[index];
You are advancing the pointer, array, in the first loop:
for(int index = 0; index < numOfElem; index++)
{
cout << "\nEnter " << index << " value";
cin >> *array++;
}
And then you pretend you are using the original, unmodified pointer in the second loop:
cout << "\n values are : " ;
for(int index = 0; index < numOfElem; index++)
{
cout << *(array+index) << ",";
}
Related
I have been coding another programming challenge from a book. It is about asking a user to input n numbers inside an array. Every time the user inputs, the current numbers entered should show up. Numbers less than or equal to zero should not be accepted. I have managed to do the first condition. However, it even shows the "empty" slots. I have tMy code will explain it. Here:
#include <iostream>
using namespace std;
int main() {
int size = 0, input_num [100], i, j;
cout << "Enter an array size: ";
cin >> size;
if (size <= 0) {
while (size <= 0) {
cout << "Enter an array size again: ";
cin >> size;
}
}
cout << "\n\nYou may now enter " << size << " numbers ";
cout << "\n------ ------ ------ ------\n";
for (i = 0; i < size; i++) {
cout << "Enter a number: ";
cin >> input_num [i];
cout << "\nEntered Numbers: ";
for (j = 0; j < size; j++) {
cout << input_num [j] << " " ;
}
cout << "\n";
}
}
In your output section, it should be j <= i, not j < size.
cout << "\nEntered Numbers: ";
for (j = 0; j <= i; j++) {
cout << input_num [j] << " " ;
}
cout << "\n";
Ok, so I'm trying to insert a space character for every odd number of j (including 0), the problem is that 0 counts as an even number (I want it to count as odd so a space character can be placed) and I'm struggling with how to figure out a solution other than playing with odd or even j. The goal is to make every element in the array have a letter and have a space character for the next index. This function is responsible for filling up the array.
void createBoard(char arr [DIM][DIM], int size){
//ASCII number for capital A
char x = 65;
for(int i = 0; i<size; i++){
for(int j = 0; j<size; j++){
if(j%2==0){
arr[i][j] = x++;
}
else{
arr[i][j] = 32;
}
cout << "Element at x[" << i << "][" << j << "]: ";
cout << arr[i][j] << endl;
}
}
}
This is function main.
const int DIM = 7;
int main()
{
char arr [DIM][DIM];
int bsize;
char answer;
do{
cout << "Please enter the size of the board [1-7]: ";
cin >> bsize;
if(!cin){
cout << endl << "Invalid entry";
break;
}
if (bsize<=DIM && bsize>=1){
createBoard(arr,bsize);
}
else{
cout << endl << "Invalid size";
cout << endl << "Do you want to try again [y-n]?: ";
cin >> answer;
}
// As long as the answer is 'y' (in upper or lower case), keep looping
}while(answer=='Y'||answer=='y');
return 0;
}
#include <iostream>
using namespace std;
int main()
{
int oldsize;
string choice;
cout << "Welcome to the Walmart Calculation Center!";
cout << endl;
cout << "Enter the Number of Items" << endl;
cin >> oldsize;
int* items = new int[oldsize];
for (int i = 0; i < oldsize; i++)
{
cout << "ENTER THE PRICE OF ITEM" << i + 1 << "!" << endl;
cin >> items[i];
}
cout << "Do you want to add more items? (YES OR NO)" << endl;
cin >> choice;
if (choice == "YES")
{
int newbie;
int newsize;
int total = 0;
while (choice == "YES")
{
newsize = oldsize + 1;
int* Nitems = new int[newsize];
for (int i = 0; i < oldsize; i++)
{
Nitems[i] = items[i];
}
cout << "Enter the Price of New ITEM!" << endl;
cin >> newbie;
Nitems[oldsize] = newbie;
oldsize = newsize;
cout << "Do you want to add more items? (YES OR NO)" << endl;
cin >> choice;
if (choice=="NO")
{
for (int i = 0; i < newsize; i++)
{
cout << Nitems[i] << endl;
}
}
}
}
}
This program is about calculating sum of the bill at a store. and ask user that if he/she wants to enter any other item, until he/she says no. In the end it displays the total bill.
You never change items array, but you change oldsize variable which represents it's size. When you the try to copy items from items to Nitems, you go out of bounds of items array (because oldsize is bigger that actual size of array).
The simplest fix would be to repoint items to Nitems at the same moment when you change the size.
while (choice == "YES")
{
newsize = oldsize + 1;
int* Nitems = new int[newsize];
for (int i = 0; i < oldsize; i++)
{
Nitems[i] = items[i];
}
cout << "Enter the Price of New ITEM!" << endl;
cin >> newbie;
Nitems[oldsize] = newbie;
oldsize = newsize;
items = Nitems; //here
cout << "Do you want to add more items? (YES OR NO)" << endl;
cin >> choice;
if (choice=="NO")
{
for (int i = 0; i < newsize; i++)
{
cout << Nitems[i] << endl;
}
}
}
See the line marked with comment? It makes items pointer point to the same array as Nitems. There is no copying involved, if you change items[1], Nitems[1] would see the same change. But having two pointers to the same array let's you keep the current array when you create new array in the next iteration.
There is of course problem with memory leaks, but don't worry too much about that until you learn how to manage memory properly. Badly placed delete is much worse that memory leak (especially in such small programs).
And of course, your code would be much simpler if you used std::vector:
std::vector<int> items;
while (choice == "YES")
{
cout << "Enter the Price of New ITEM!" << endl;
cin >> newbie;
items.push_back(newbie);
cout << "Do you want to add more items? (YES OR NO)" << endl;
cin >> choice;
if (choice=="NO")
{
for (int i = 0; i < items.size(); i++)
{
cout << items[i] << endl;
}
}
}
I am unable to comment due to low reputation. But I feel you are still unclear about dynamic allocation concepts. You will need to delete if you create something using new to avoid memory leaks. This program can be much simpler like below. I still use new deliberately to show the delete scenario. Apart from that you also need to clear up some basics as given in comments. All the best!
#include <iostream>
using namespace std;
int main()
{
int oldsize, newbie;
int total=0;
string choice;
cout << "Welcome to the Walmart Calculation Center!";
cout << endl;
cout << "Enter the Number of Items" << endl;
cin >> oldsize;
int* items = new int[oldsize];
for (int i = 0; i < oldsize; i++)
{
cout << "ENTER THE PRICE OF ITEM" << i + 1 << "!" << endl;
cin >> items[i];
total+=items[i];
}
do {
cout << "Do you want to add more items? (YES OR NO)" << endl;
cin >> choice;
//if user inputs NO, break out of do while.
if(choice == "NO") break;
//continue here if YES
cout << "Enter the Price of New ITEM!" << endl;
cin >> newbie;
total+=newbie;
}while(choice=="YES");
cout << "Total: " << total << endl;
delete[] items;
}
This program is supposed to accept values from the keyboard, and require that the user re-enter the value for the employee's id number. However it keeps outputting "Invalid variable" even if I enter a correct value. It needs to only output that if the value is already been entered. For example
if I enter "3453" as the id number it will still output "Invalid Variable" even if I have not entered that number before.
#include <iostream>
using namespace std;
struct Employee
{
int idNum;
double payRate;
char firstName, lastName;
};
int main()
{
int error;
const int SIZE = 5;
Employee employee[SIZE];
for (int k = 0; k < SIZE; ++k)
{
employee[k].idNum = 0;
employee[k].payRate = 0;
}
for (int count = 0; count < SIZE; ++count)
{
error = 0;
cout << "Enter the employee's id number " << endl;
cin >> employee[count].idNum;
for (int i = 0; i < SIZE; ++i)
{
if (employee[i].idNum == employee[count].idNum)
error = 1;
}
while (error == 1)
{
cout << "Invalid entry. Please enter a new id number " << endl;
cin >> employee[count].idNum;
for (int i = 0; i < SIZE; ++i)
{
error = 0;
if (employee[i].idNum == employee[count].idNum)
error = 1;
}
}
cout << "Enter the employee's pay rate " << endl;
cin >> employee[count].payRate;
cout << "Enter the employee's first name " << endl;
cin >> employee[count].firstName;
cout << "Enter the employee's last name " << endl;
cin >> employee[count].lastName;
int choice;
cout << "Enter 1 to search for an employee by id number, enter 2 to search by last name, and enter 3 to search by pay "
<< endl;
cin >> choice;
}
int choice;
cout << "Enter 1 to search for an employee by id number, enter 2 to search by last name, and enter 3 to search by pay "
<< endl;
cin >> choice;
if (choice == 1)
{
int idNumC;
cout << "Enter an id number ";
cin >> idNumC;
for (int count = 0; count < SIZE; ++count)
{
if (employee[count].idNum == idNumC)
cout << employee[count].idNum;
}
}
if (choice == 2)
{
char name;
cout << "Enter the employee's last name " << endl;
cin >> name;
for (int count = 0; count < SIZE; ++count)
{
if (employee[count].lastName == name)
cout << "ID number: " << employee[count].idNum
<< " First name: " << employee[count].firstName
<< " Last Name: " << employee[count].lastName
<< " Hourly Pay: " << endl;
}
}
if (choice == 3)
{
int name;
cout << "Enter the employee's last name " << endl;
cin >> name;
for (int count = 0; count < SIZE; ++count)
{
if (employee[count].payRate == name)
cout << "ID number: " << employee[count].idNum
<< " First name: " << employee[count].firstName
<< " Last Name: " << employee[count].lastName
<< " Hourly Pay: " << endl;
}
}
}
My program also will not accept a value of more than one letter into the name. If I try and enter that into the program, the program keeps printing "Invalid entry" until I hit ctrl+c.
for (int i = 0; i < SIZE; ++i)
This checks every element in the array, including the one you have just read. You probably meant to put
for (int i = 0; i < count; ++i)
which will check every element up to (but not including) the one you have just read.
in
for (int i = 0; i < SIZE; ++i)
{
if (employee[i].idNum == employee[count].idNum)
error = 1;
}
employee[count] is one of the employee[i] you're going to compare against which means at some point you will
if (employee[count].idNum == employee[count].idNum)
Which is guaranteed to be true.
But if instead you
int tempId;
cin >> tempId;
for (int i = 0; i < SIZE; ++i)
{
if (employee[i].idNum == tempId)
error = 1;
}
and then set
employee[count].idNum = tempId;
at some later time, you can avoid this problem.
Addendum: I recommend picking this logic up and placing it in its own function. That way A) you don't have to repeat it inside the loop a few lines down where you're repeating the check for each retry and it gets the logic out of the way of the rest of the code. B) you can use the same function later for any other "Does this employee exist?" checks you need to write in the future.
In general You want to have lots of simple, easily-tested functions over one monolithic jack-of-all-trades.
How come when I do fractionAry[i] = new Fraction(num1, denom1) it works and stores the created fraction into index of i.
But when I do fractionAry[i][j] = new Fraction(num1, denom1), the compiler gives me an error saying that no operator matches these operands?
If I would like to store the fraction into j, how would I do that? I am not entirely sure how to store a fraction into an array of array of fractions...
Here's my code, thanks for the help ahead of time.
void createArray() {
Fraction** fractionAry;
int aryCount;
int arySize;
int i, j;
int num1, denom1;
cout << "\nHow many arrays of fractions (treating these as array of arrays of fractions? ";
cin >> aryCount;
if (aryCount > 0) {
fractionAry = new Fraction*[aryCount];
for (i = 0; i < aryCount; i++) {
cout << "\nCreating array index # " << i
<< "\n How many fractions(s)? ";
cin >> arySize;
if (arySize > 0) {
fractionAry[i] = new Fraction[arySize + 1];
fractionAry[i][0] = arySize;
for (j = 1; j < arySize + 1; j++) {
cout << "\n Enter the numerator: ";
cin >> num1;
cout << " Enter the denominator: ";
cin >> denom1;
while (denom1 == 0) {
cout << "\nCan't set to 0! Enter a new denominator: ";
cin >> denom1;
}
fractionAry[i] = new Fraction(num1, denom1);
// fractionAry[i][j] = new Fraction(num1, denom1); I would like to do this instead
}
cout << "\nFor array index #" << i << endl;
for (j = 0; j < arySize + 1; j++) {
cout << " Element index #" << j << " : " << *(*(fractionAry + i) + j) << endl;
}
}
}
}
}
Instead of having fractionAry[i][j] = new Fraction(...) use fractionAry[i][j] = Fraction(...). The type at fractionAry[i][j] is Fraction not Fraction* which is what the new operator returns.
void createArray() {
Fraction** fractionAry;
int aryCount;
int arySize;
int i, j;
int num1, denom1;
cout << "\nHow many arrays of fractions (treating these as array of arrays of fractions? ";
cin >> aryCount;
if (aryCount < 1)
{
//print error message or exit function
}
fractionAry = new Fraction*[aryCount];
for (i = 0; i < aryCount; i++)
{
cout << "\nCreating array index # " << i
<< "\n How many fractions(s)? ";
cin >> arySize;
if (arySize < 1)
{
//Print error message decrement i and continue or exit function
}
fractionAry[i] = new Fraction[arySize + 1];
//I don't understand the purpose of assigning the below value or making the array one size bigger
fractionAry[i][0] = arySize;
///
for (j = 1; j < arySize + 1; j++)
{
cout << "\n Enter the numerator: ";
cin >> num1;
cout << " Enter the denominator: ";
cin >> denom1;
while (denom1 == 0)
{
cout << "\nCan't set to 0! Enter a new denominator: ";
cin >> denom1;
}
fractionAry[i][j] = Fraction(num1, denom1);
}
cout << "\nFor array index #" << i << endl;
for (j = 0; j < arySize + 1; j++)
{
cout << " Element index #" << j << " : " << fractionAry[i][j] << endl;
}
}
}