Initialize int array with length of a input string in c++ [duplicate] - c++

This question already has answers here:
Array size at run time without dynamic allocation is allowed? [duplicate]
(8 answers)
Closed 7 years ago.
I receive these errors
1. cannot allocate an array of constant size 0
2. expected constant expression
3. 'numbers' : unknown size
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str;
int input_num;
int sum;
cout << "Enter the number:" << endl;
getline(cin, str);
const int length = str.length();
cout << "Length:" << length<<endl;
//input_num = stoi(str);
int numbers[length];
return 0;
}

Replace the use of an array by a std::vector, and initialize the elements to 0.
std::vector<int> numbers(length, 0);

The size of an array has to be a constant expression greater than 0.
You should use standard class std::vector<int> instead.
For example
#include <vector>
//...
std::vector<int> numbers( length );
If the user has to enter a number of type for example int (that is the number might be in the range of acceptable values of object of type int) then you could define the array beforehand the following way
#include <limits>
//...
int numbers[std::limits<int>::digits10 + 1];

Related

Can I pass a 2D array that a user created? [duplicate]

This question already has answers here:
How to implement 2D vector array?
(9 answers)
How do I declare a 2d array in C++ using new?
(29 answers)
Closed 1 year ago.
I'm trying to pass a 2D array into a function with the user's input (asking the user for the number of columns, rows, etc. Here's the code I have. Is there a way to pass the function with said inputs?
#include <iostream> // Input and output
#include <iomanip> // Input manipulator
#include <array>
using namespace std;
int rows;
int columns;
int getTotal(int array[][columns], int, int);
int main()
{
cout << "How many rows would you like to have in your array? " << endl;
cin >> rows;
cout << "How many rows would you like to have in your array? " << endl;
cin >> columns;
int userArray[rows][columns];
getTotal(userArray, rows, columns); // This column will not call the function
return 0;
}
int getTotal(int userArray[][columns], int rows, int columns)
{
// function to add all numbers
}

How can I take array input of any size? I tried doing with this code but don't know where the error is. Please Help me Out [duplicate]

This question already has answers here:
C++ : Creating an array with a size entered by the user
(3 answers)
Closed 1 year ago.
How can I take array input of any size? I tried doing with this code but don't know where the error is. Please Help me Out
#include <iostream>
using namespace std;
int main()
{
int arr[10000];
int i;
int arrSize = sizeof(arr)/sizeof(arr[0]);
if(i=0; i<arrSize; i++)
{
cin>>arr[i];
}
cout << "The size of the array is: " << arrSize;
return 0;
}
Try using for instead of if. Also, no need to do that sizeof thing. Just put the size of the array there or take the number of elements as an input from the user.

How can I discover the amount of elements in an array in C++ [duplicate]

This question already has answers here:
How to find the size of an array (from a pointer pointing to the first element array)?
(17 answers)
C sizeof a passed array [duplicate]
(7 answers)
Closed 4 years ago.
I'm facing some problems with my code in C++. I would like to know how can I discover the amount of elements in an array. Follow the code:
#include <iostream>
#include <cstdlib>
using namespace std;
int avg(int numbers[]){
int amount; // The problem is in. How can I discover the amount of elements in an array?
int sum = 0;
for(int i = 0; i < amount; i++){
sum += numbers[i];
}
return sum / amount;
}
int main(){
int q;
cout << "Type number of integers:" << endl;
cin >> q;
int numbers[q];
for(int i = 0; i < q; i++){
cout << "Type an integer value for number " << i+1 << ":" << endl;
cin >> numbers[i];
}
cout << "The average is " << avg(numbers) << endl;
return 0;
}
The standard array in C++ doesn't contain a way to access the size of the array, the best way to track this is to have an integer that is updated with the size of the array or to try using std::array and then use the .size() method.
In your example you are using a fixed size array anyway so you may want to store the q value as a member variable and that contains the array size. Notice that in your example the code will not work as q is not a constant integer. To declare an array without a constant integer you will need to use a pointer to the first element of the array ie: int* numbers = new int[q];.

Displaying numbers from a user created array c++ [duplicate]

This question already has answers here:
getting size of array from pointer c++
(6 answers)
Closed 7 years ago.
Alright so this is probably a really simple question, I'm just really new to c++ and am struggling to understand most things. I've been asked to create an array that stores random numbers but the user is to define the size of the array. I then have to display all the numbers in the array. What I'm struggling with is displaying all elements of the array. At the moment, I'm pretty sure I've got the array part down, but I can only seem to display one number. Here's my code so far:
#include <iostream>
#include <cstdlib>
#include <stdlib.h>
#include <ctime>
using namespace std;
using std::srand;
using std::rand;
using std::time;
void Display(int *, int);
int main(void)
{
int userSize;
cout << "Please enter the size of the array: ";
cin >> userSize;
int* randArray = new int[userSize];
srand(time(NULL));
for (int i = 0; i < userSize; i++) {
randArray[i] = rand() % 20 + 1;
}
//Disregard the next few lines, I was just testing to see if anything was actually in the array.
/*cout << randArray[0] << endl;
cout << randArray[1] << endl;
cout << randArray[2] << endl;
cout << randArray[19] << endl;*/
Display(randArray, sizeof(randArray) / sizeof(int));
return 0;
delete[] randArray;
}
void Display(int *arrayData, int numElements)
{
for (int counter = 0; counter < numElements; counter++)
{
std::cout << *(arrayData + counter) << std::endl;
}
return;
}
I should also mention that the teacher provided us with the code after the line that deletes the array.
This is the question I have to answer: Ask the user for the number of elements to be stored in the array. You should then dynamically allocate the memory to hold this array, which will proceed to be used in the same way as the previous task (populating the array with random data, displaying the data to the
screen).
sizeof(randArray) does not tell you the number of bytes that you've allocated. Rather, it tells you the size of a pointer, which on your system happens to be the same as the size of an integer, so sizeof(randArray) / sizeof(int) returns 1 always. Instead use userSize as your second parameter in the function call to Display.
Also, you delete[] randArray after return 0. This is incorrect; nothing after the return 0 will be executed. You want it above instead.
Further, consider the use of std::vector instead (unless you are required to use a raw pointer for this assignment)
The problem is sizeof. It gives you the size of the type of the argument, not of what is behind. Your should pass userSize to Display().
You should also delete the array before you return. Code behind return never gets executed.

Pointer to a C-String? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
For an intro to CS assignment, I am writing a C++ program in Visual Studio 2010 which returns an integer and accepts a pointer to a C-string as an argument. I know that I need to make a function besides an int main to succeed, but I am not exactly sure about how to initialize a char pointer array which points to a predefined char array, if possible.
The purpose of this program is to get a comment from a user within a predefined limit then inform said user how many characters (including whitespace) that comment is.
The error is: a value of type "char" cannot be assigned to an entity of type "char *";
Here is my program that does not compile:
#include "stdafx.h"
#include <iostream>
#include <string>
#include <conio.h>
using namespace std;
//function protoype
void evalStr(char arr[]);
//variable
int length;
//main function
int main()
{
const int SIZE = 201;
char arr[SIZE];
char *str[SIZE];
cout << "Please enter a comment under " << (SIZE - 1) << " characters to calculate it's length: ";
*str = arr[SIZE];
cin.getline(arr, SIZE);
length = strlen(*str);
evalStr(arr);
system("PAUSE");
return 0;
}
//function defintion
/* get the string
count the number of characters in the string
return that number
*/
void evalStr(char arr[])
{
printf("The length of the entered comment is %d characters\n", length);
}
If there is a general method to utilizing char pointer arrays or perhaps pointers to strings, this code could be redone to return the value of the string instead of utilizing that printf statement. What all am I doing wrong?
Edit: Here is an updated version of this program that compiles, runs, and informs the user if the character limit is reached or exceeded.
// Accept a pointer to a C-string as an argument
// Utilize the length of C-string in a function.
// Return the value of the length
// Display that value in a cout statement.
#include "stdafx.h"
#include <iostream>
#include <string>
#include <conio.h>
using namespace std;
//variables
const int SIZE = 201;
int length;
char arr[SIZE];
char *str;
//main function
int main()
{
str = &arr[0];
// Size - 1 to leave room for the NULL character
cout << "Please enter a comment under " << (SIZE - 1) << " characters to calculate it's length: ";
cin.getline(arr, SIZE);
length = strlen(str);
if (length == (SIZE - 1))
{
cout << "Your statement has reached or exceeded the maximum value of "
<< length << " characters long.\n";
}
else
{
cout << "Your statement is ";
cout << length << " characters long.\n";
}
system("PAUSE");
return 0;
}
//function defintion
/* get the string
count the number of characters in the string
return that number
*/
int countChars(int)
{
length = strlen(str);
return length;
}
Let's talk about what is happening in main instead:
int main()
{
Okay, so you're going to have strings of 201 characters. Seems reasonable.
const int SIZE = 201;
And you've declared an array of 201 characters:
char arr[SIZE];
And now you declare an array of 201 pointers to characters. I'm not sure why you would want to do that. I suspect you think this does something other than what it actually does:
char *str[SIZE];
This is reasonable (except "it's" means "it is", but you want the possessive version, "its"):
cout << "Please enter a comment under " << (SIZE - 1) << " characters to calculate it's length: ";
This assigns the 201st character to the first character pointer in your array of char pointers. This is an error because:
arrays are zero-indexed, so the 201st character (when you start counting at zero) is beyond the end of the array.
you haven't initialized the memory in arr to anything yet.
you're assigning a char to a char *.
So, given the above I'm not sure why you're doing this:
*str = arr[SIZE];
This looks reasonable:
cin.getline(arr, SIZE);
This is an error because str doesn't point to memory that contains a valid string at this point.
length = strlen(*str);
When you "point to a string", actually you point to the first character of the string. The end of the string can be found by looking at successive memory locations until you find a location containing a null byte. So your code should be:
char *str; // can point at a character
// ....
str = &arr[0]; // point to the first character of arr
// ....
length = strlen(str);