For a program I must use an array and not vector. I have to take in user's input, and it's a indefinite amount of them. The user can type in 5 values, or 50. I am absolutely stumped as to how to go about doing this. Using a for loop for example:
Int a[10];
Int b;
For (int i=0; i<10; i++)
{
Cout<<"enter values:";
Cin>>b;
A[i]=b;
}
With this I can take an array of 10 of user defined variables but how would I go about making it a dynamic size? Thank you for the help!
The size of a static array must be known at compile time, otherwise you must use a dynamic array. For example
#include <iostream>
int main()
{
// Determine how many total entries are expected
int entries;
std::cout << "How many values do you want to enter?" << std::endl;
std::cin >> entries;
// Allocate a dynamic array of the requested size
int* a = new int[entries];
// Populate the array
for (int i = 0; i < entries; ++i)
{
std::cout << "enter a value: ";
std::cin >> a[i];
std::cout << std::endl;
}
// Clean up your allocated memory
delete[] a;
return 0;
}
Related
Here is the assignment:
Your goal is to write a program that displays a series of whole numbers from input in reverse order. Your
program will prompt the user for the number of values in this list, which it will use as the size for a dynamic
array declared after this prompt.
The array size is unknown, the value is the pointer, and the sub has to be assigned before the loop.
Here are the steps:
Declare variables, but don't "allocate the memory the memory for the pointer yet". Do this after prompting the user to enter the values.
Prompt user to enter the numbers of values to be listed. (There has to be a message for the user in case they enter a negative number). Then use the keyword new for the pointer.
Prompt the user to enter the values
Display the values in reverse.
Use the keyword delete for the dynamic array.
While I'm trying to run the program, the error was:
error: ISO C++ forbids comparison between pointer and integer [-fpermissive]
for(int sub = 0; sub < size; size--)
--------------------------------------^
error: lvalue required as decrement operand
for (int sub = 0; sub > size; size--)
------------------------------------------------------^
Also, I am not sure what the keyword new does.
#include <iostream>
using namespace std;
int main()
{
int size, array;
cout << "How many values would you like to enter? ";
cin >> array;
int value;
int *array = new int[size];
if (size > 0)
{
for (int sub = 0; sub < size; size++)
{
cout << "Enter value #" << size << ": ";
cin >> value;
}
while (size > 0);
}
else
{
while (size < 0)
{
cout << "Size must be positive." << endl;
cout << "How many values would you like to enter? ";
cin >> size;
}
}
cout << "Here are the values you entered in reverse order: \n";
for (int sub = size - 1; sub >= 0; size--)
{
cout << "Value #" << size << " :" << value << endl;
}
delete[] array;
return 0;
}
PS: I know size is supposed to be unknown, but I've encountered another error saying
storage size of ‘size’ isn’t known
So, I add numbers to avoid that error.
Edit:So I changed the code thanks to #MikeCAT, but this error said terminate called after throwing an instance of 'std::bad_array_new_length what(): std::bad_array_new_length. This was because I enter a negative number for the size, which was supposed to happen for the if statement. Also, I need the size to start at 1 after the user enters how many values they want to enter, but the size always starts at the number that was entered.
As the assignment says, you should
Read a value
Allocate a dynamic array using the value read as its size
Read the numbers for the array
#include <iostream>
int main(void) {
// read a number (size of a dynamic array)
int numElements;
std::cin >> numElements;
// allocate a dynamic array
int *array = new int[numElements];
// read values for the dynamic array
for (int i = 0; i < numElements; i++) {
std::cin >> array[i];
}
// print the values in reversed order
for (int i = numElements - 1; i >= 0; i--) {
std::cout << array[i] << '\n';
}
// de-allocate the array
delete[] array;
// exit normally
return 0;
}
Error handling and non-essensial messages are omitted. Try adding them.
Could someone explain why pointers gets overwritten when variables are declared inside a loop?
For example, given the following snippet, and the user inputs 1 and 2. I would expect that the pNums array contain 2 pointers to 2 integers holding the value 1 and 2 respectively.
But instead, the console prints out 2 and 2;
#include <iostream>
using namespace std;
//Input "1 2"
int main() {
int* pNums[2];
for(int i = 0; i < 2; i++){
int num;
cin >> num;
pNums[i] = (&num);
}
cout << (*pNums[0]) << endl;
cout << (*pNums[1]) << endl;
}
Why is this the case? And how do I get around it? What if, for example, we don't know how many numbers the user will put in, and instead of a for loop, we have a while loop? Until some conditions are met, we want to keep creating new pointers and store them into a pNums vector?
There is only one num, and you are overwriting that. (And then causing Undefined Behavior, but never mind that.)
There are two simple ways to avoid this mistake.
1) Store objects, not pointers:
int nums[2];
for(int i = 0; i < 2; i++){
cin >> nums[i];
}
2) Use dynamic allocation:
int* pNums[2];
for(int i = 0; i < 2; i++){
int *p=new int;
cin >> *p;
pNums[i] = p;
}
The pointers that you are storing in pNums are to two instances of the variable num in the for block. There is one instance of the variable in each for loop iteration and these variables live only until the end of their respective iteration of the for loop body is reached.
Therefore your pointers will be invalid when the for loop exits and so trying to dereference them with e.g. *pNums[0] causes undefined behavior.
Don't store pointer, store values:
#include <iostream>
using namespace std;
//Input "1 2"
int main() {
int pNums[2];
for(int i = 0; i < 2; i++){
int num;
cin >> num;
pNums[i] = num;
}
cout << pNums[0] << endl;
cout << pNums[1] << endl;
}
and if you need a variable number of entries in the array, use std::vector.
for(int i = 0; i < 2; i++){
int num; //< this is num. It lives here.
cin >> num;
pNums[i] = (&num); //< you have taken the address of num (twice!)
}
// here is when 'num' is destroyed (no longer in scope)
// so this is now pointing at something that doesn't exist.
cout << (*pNums[0]) << endl;
I'm learning c++ and I'm trying to ask the user to input 4 numbers in a function, and then simply print the array.
int getFourNums();
int main(int argc, char** argv){
int getNums;
getNums = getFourNums();
cout << "The array is: " getNums << endl;
}
int getFourNums(){
int i;
int myArray[4];
cout << "Enter 4 nums: ";
for(i = 0; i < 4; i++){
cin >> myArray[i];
}
return myArray[i];
As of now, it's letting me get the four numbers, but the result that's printing is "The array is: 0." I'm not quite sure why the array is seemingly not populating.
Your fundamental problem is that int getFourNums() can only return a single integer, not an array of them. The next problem is that functions cannot return raw arrays for historical reasons. Your choices are to return a std::array, a struct containing the array, pass the array by reference into the function, or return a std::vector. My preference for this application is a std::vector - it is flexible, and although not quite as efficient as std::array, you should probably default to std::vector unless you have a good reason otherwise. Your getNums code would then look like:
std::vector<int> getFourNums() {
std::vector<int> result;
cout << "Enter 4 nums: ";
for(int i = 0; i < 4; i++){
int v;
cin >> v;
result.push_back(v);
}
return result;
}
To print the vector, see this question. My personal preference would be a range-based for loop over the vector; your tastes may vary.
One issue in your code is that a loop like
for(i = 0; i < 4; i++){
cin >> myArray[i];
}
will end up with i==4. Hence, return myArray[i] will exceed array bounds and/or access an uninitialised value then and yield undefined behaviour.
The main issue, however, is that in C++ you'll follow a very different approach and use collection types like std::vector instead of plain arrays. See the following code illustrating this. Hope it helps.
#include <vector>
#include <iostream>
std::vector<int> getFourNums(){
int val;
std::vector<int> result;
cout << "Enter 4 nums: ";
for(int i = 0; i < 4; i++){
cin >> val;
result.push_back(val);
}
return result;
}
int main(int argc, char** argv){
std::vector<int> fourNums = getFourNums();
for (auto i : fourNums) {
cout << i << endl;
}
}
int getFourNums() will only let you return one int, not the whole array and return myArray[i]; is out of bounds since i == 4. You can only use the range [0,3] as indices for your array. Here's a reworked version with comments in the code.
#include <iostream>
#include <vector>
// don't do "using namespace std;" since it includes
// a lot of stuff you don't need.
// Here's a function that will return a vector of int's
// It'll behave much like a C style array
// but can have variable length and you can use
// a lot of standard functions on it.
std::vector<int> getNums(size_t count) {
// The "array" we'll return with "count" number of
// default constructed int:s (they will all be 0):
std::vector<int> myArray(count);
std::cout << "Enter " << count << " nums: ";
// A range based for loop that will go through
// all int:s in "myArray". "num" will be
// a reference to each int in the vector which
// means that if you change the value of "num",
// you'll actually change the value in the vector.
for(int& num : myArray) {
// read values into the int currently
// referenced by num
std::cin >> num;
}
// return the vector by value
return myArray;
}
// Put main() last so you don't have to forward declare the functions
// it uses
int main() {
// call getNums with the value 4 to read 4 int:s
std::vector<int> Nums = getNums(4);
std::cout << "The array is:";
// print each int in the vector. There's no need to use
// a reference to the int:s here since we won't be changing
// the value in the vector and copying an int is cheap.
for(int num : Nums) {
std::cout << " " << num;
}
// std::endl is rarely good when you only want to output a newline.
// It'll flush the buffer with is costly.
// Make a habit of using "\n" in most cases.
std::cout << "\n";
}
I see that you want to return entire array but just look at your return type:
int getFourNums()
You're returning an integer right? In this situation the returned integer is always myArray[4]. Be aware that it's an integer value, you're returning something that doesn't belong to you actually!
So what to do? I suggest you to pass your array to function like this:
void getFourNums(int myArray[]){
int i;
cout << "Enter 4 nums: ";
for(i = 0; i < SIZE; i++){
cin >> myArray[i];
}
}
Now you filled your array. How to print your array then? We can't simply give our array name and tell cout to print it like you did (you couldn't actually!). Nothing magical here. We're going to print your array's element one by one:
void printFourNumbers(int array[])
{
for(int i = 0 ; i < SIZE ; ++i)
{
cout << array[i] << endl;
}
}
Finally whole code looks like this:
#include <iostream>
using namespace std;
const int SIZE = 4;
void getFourNums(int myArray[]);
void printFourNumbers(int array[]);
int main(int argc, char** argv){
int myArray[SIZE];
getFourNums(myArray);
printFourNumbers(myArray);
}
void getFourNums(int myArray[]){
int i;
cout << "Enter 4 nums: ";
for(i = 0; i < SIZE; i++){
cin >> myArray[i];
}
}
void printFourNumbers(int array[])
{
for(int i = 0 ; i < SIZE ; ++i)
{
cout << array[i] << endl;
}
}
I created a simple program to help me understand how to Dynamically Allocate a structure. I want the program to gets 5 names and 5 accounts from the user, and display the names and the accounts. I know a pointer is like a reference variable, the only differences instead of passing the value, it passes the address of the variable. I set a breaking point for line 23 ("getline(std::cin,clientPtr[count].name);"), line 25 ("std::cin.ignore(std::numeric_limits::max(),'\n');"),
line 27 ("std::cin >>clientPtr[count].accounts;"), line 40 ("std::cout <<"Name:" << clientPtr[count].name;"), line 41 ("std::cout <<"Name:" << clientPtr[count].name;"),line 31( showInfo(&client);). When I debugged it shows that line 41 is not executing. It should display the names and the accounts of each client. In this case it's not. I'm not sure why, just a little background on me, I'm new to C++, as well with using the debugger. I'm using xcode 8.2 and the debugger I am using is lldb. I'm here to learn, so anything will help. Thanks.
#include <iostream>
#include <limits>
struct BankInfo
{
std::string name;
std::string accounts;
};
void showInfo(BankInfo*);
int main()
{
BankInfo client;
BankInfo* clientPtr=nullptr;
clientPtr = new BankInfo[5];
for(int count =0; count < 5; count++)
{
std::cout << "Enter your name:";
getline(std::cin,clientPtr[count].name);
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
std::cout << "Enter you account number:";
std::cin >>clientPtr[count].accounts;
}
showInfo(&client);
return 0;
}
void showInfo(BankInfo* clientPtr)
{
for(int count =5; count < 5; count++)
{
std::cout <<"Name:" << clientPtr[count].name;
std::cout <<"Account:" << clientPtr[count].accounts;
}
}
You are handing the wrong thing to showInfo(). You have two variables.. a single BankInfo variable and a dynamic allocated array with size 5.
You want to iterate over the latter and not the former.
Changing showInfo(&client);to showInfo(clientPtr); should do the trick perhaps?
So I fixed the solution I made several mistakes, but thank you for the suggestion. Here's what I did.
#include <iostream>
#include <limits>
struct BankInfo
{
std::string name;
std::string accounts;
};
void showInfo(BankInfo*);
int main()
{
BankInfo client;
BankInfo* clientPtr=nullptr;
clientPtr = new BankInfo[5]; //Allocate an array of BankInfo struct on the heap
for(int count =0; count < 5; count++)
{
std::cout << "Enter your name:";
getline(std::cin,clientPtr[count].name); // stores the value in the name member
std::cout << "Enter you account number:";
std::cin >>clientPtr[count].accounts; // stores the value in accounts member
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
}
showInfo(clientPtr);
delete [] clientPtr;
clientPtr = nullptr;
return 0;
}
void showInfo(BankInfo* clientPtr)
{
for(int count =0; count < 5; count++)
{
std::cout <<"\nName:" << clientPtr[count].name; // dereference the pointer to the structure
std::cout <<"\nAccount:" << clientPtr[count].accounts; // dereference the pointer to the structure
}
}
for(int count=1 ; count<=5 ; count++)
{
//do your stuff here
}
I am trying to create an array using cin to define the size. While that seems to be working (based on what I currently have), none of the other stuff I want to do seems to be working.
For instance, I want to use a for loop to find the smallest int in the array since I will then need to compare it with all the other ints in the array, but no matter where I have the statement to return the smallest int, it does not do it.
What am I doing wrong?
#include <iostream>
using namespace std;
int main(){
int userSize;
cout << "Please define size of array: ";
cin >> userSize;
int *duckArray = new int[userSize];
for (int i = 0; i < userSize; i++) {
cout << "Please enter a number into the array: ";
cin >> duckArray[i];
}
int smallest = duckArray[0];
for (int i = 0; i < userSize; i++){
if (duckArray[i] < smallest){
smallest = duckArray[i];
cout << smallest << endl;
}
}
//cout << smallest << endl;
return 0;
}
Your code is working if you change this:
for (int i = 0; i < userSize; i++){
if (duckArray[i] < smallest){
smallest = duckArray[i];
}
}
cout << smallest << endl;
This will find and print the smallest number entered.
Arrays in C++ must have their size declared to the compiler at runtime. Other people are going to explain how you can buffer memory to simulate a dynamically allocating arrays. You can also have your Array at a given size and as the user adds and removes, you can reject inputs over the current size.
I highly recommend you look into Vectors. Vectors are much like ArrayLists in Java. They are a form of higher level collections that resize themselves as you add more elements to them.