I am getting all kinds of errors when passing my array to this function. The function is suppose to have the user enter a name and a score and store them in 2 seperate arrays, one for the names, one for the scores. I believe I have to use pointers but have no idea on how to use them. I don't want the answer, just a push in the right direction. Here is the code:
#include <iostream>
int InputData(int &, char, int);
using namespace std;
int main()
{
char playerName[100][20];
int score[100];
int numPlayers = 0;
InputData(numPlayers, playerName, score);
return 0;
}
int InputData(int &numPlayers, char playerName[][20], int score[])
{
while (numPlayers <= 100)
{
cout << "Enter Player Name (Q to quit): ";
cin.getline(playerName, 100, ā\nā);
if ((playerName[numPlayers] = 'Q') || (playerName[numPlayers] = 'q'))
return 0;
cout << "Enter score for " << playerName[numPlayers] <<": ";
cin >> score[numPlayers];
numPlayers++;
}
}
Ok, I made some more changes and the errors are less, must be getting close, Lol!
This looks like a school assignment and I applaud you for not asking for the answer. There are several ways to do it, but you are already fairly close in the approach that you are using. When you pass an array reference, you do not want to include the length of the array. For example, the parameter int score[100] should be int score[]. The exception, especially in your scenario, is with multidimensional arrays. In this case, you want to use char playerName[][20]. Your function declaration also needs to change to match. Don't forget InputData returns an int. Your declarations and function call are correct; you just need to adjust your function signature.
Keeping the errors aside -
InputData(numPlayers, playerName, score, size);
// ^^^^ size is no where declared
// resulting Undeclared indentifier error
Prototype mentions of taking 3 arguments but calling the function passing 4 parameters.
Hint regarding errors:
An 1D array decays to a pointer pointing to first element in the array while passing to a function.
A 2D array decays to a pointer pointing to the 1D array ( i.e., T[][size] ) while passing to a function.
Return type of main() should be int.
It seems with the given hints you corrected most of the errors. But you forgot to change the prototype. So, change -
int InputData(int &, char, int);
to
int InputData(int &, char[][20], int[]);
Why aren't you using std::string array for player names ? Use it and remove rest of the errors. Good luck.
Related
I want to make an array, and inside this array there are pointers, like this:
int *arrp[size]; and I want the user to enter the size of it.
I tried to do this:
#include <iostream>
using namespace std;
int main ()
{
int size;
cout << "Enter the size of the array of pointers" << endl;
cin >> size;
int *arrp[size];
return 0;
}
but this doesn't work.
I also tried to do this:
#include <iostream>
using namespace std;
int main ()
{
int size;
cout << "Enter the size of the array of pointers" << endl;
cin >> size;
int* arrp[] = new int[size];
return 0;
}
also doesn't work, can someone help?
The error of the first code is that the size must be constant, I tried to fix that by writing the 2nd code but it gives an error for the word "new" in line 9:
E0520 initialization with '{...}' expected for aggregate object
and another error for the size in the same line:
C2440 'initializing': cannot convert from 'int *' to 'int *[]'
To make an array of pointers you should type: int** arr = new int*[size]
we type 2 stars '*', the first mean a pointer to an integer, the second means a pointer to the pointer to the integer, and then we make a place in the memory for those pointers by typing = new int*[size], you can use this as a 2D array that stored in the heap (not the stack) go to this website to know the difference: https://www.geeksforgeeks.org/stack-vs-heap-memory-allocation/.
to know more about how to use an array of pointers to a pointer to an integers you can see this video: https://www.youtube.com/watch?v=gNgUMA_Ur0U&ab_channel=TheCherno.
I'm trying to write a program that will ask the user to enter "how many numbers they want to add", then add all the numbers in a function. I want to create the adding function with a dynamically allocated number of parameters such that there are X "int num{someNumber}," where X is the number of numbers the user wants to add. My current code (very rough) is:
int var = 0;
string multiply(int num);
void testing(int num, multiply(var));
int main(){}
void testing(int num, multiply(var)) {
}//end testing
//Function to append int num{num} to string
string multiply(int num) {
string declaration = "null";
for (int num = 0; num <= var; num++) {
declaration.append("int num" + num);
}//end for
return declaration;
}//end multiply
I realize that there is still work to be done, like removing the last comma, for instance, but is it possible to use a string in a function definition to declare X int num parameters?
Another similar question already exists, check out its answer: Variable number of arguments in C++?
While it is definitely possible to define functions with a variable number of arguments, you may also want to consider defining your program iteratively or recursively instead.
Functions with a variable number of arguments can be very useful at times, but can also lead to strange edge-cases like scanf("%d") which wants to scan an integer, but is not given an address to place it into. The function call is allowed, and the scanned integer overwrites a (possibly important) location in memory.
The compiler is displaying garbage value when coded as follows:
#include<iostream>
using namespace std;
void summation(int value1,int value2, int sum)
{
sum = value1+value2;
}
int main()
{
int a,b,sum;
cout<<"enter first no.\n";
cin>>a ;
cout<<"enter the second no.";
cin>>b ;
summation(a,b,sum);
cout<<"the addition of two no. is :" <<sum ;
return 0;
}
Obtaining correct input on writing &sum instead of sum. Why is it so?
You are passing sum to the summation() method by value and you want to pass it by reference. Try defining your method like this:
void summation(int value1,int value2, int& sum)
{
sum = value1+value2;
}
When you pass a parameter by its value (like you did), the method creates a copy of the value of the parameter and works with the copy. In the result, the passed parameter (sum) outside of the method stays unchanged. When you pass a parameter by its reference ( int& sum ), the sum variable inside your method will be the same as the sum variable in your main method and you can make changes to it.
Sorry to ask, but I been looking everywhere to find a way to extract the integers from this set of strings:
{(1,2),(1,5),(2,1),(2,3),(3,2),(3,4),(4,3),(4,5),(5,1),(5,4)}
I don't really need the homework done, if you could link me to an example, I'll appreciate it.
thank you in advanced.
If you just want to access the integers from a line like that, one way is to simply continue reading integers while you can.
If, for some reason, you find an integer read failing (because there's a { in the input stream, for example), just skip over that single character and keep going.
Sample code for this is:
#include <iostream>
int main() {
int intVal; // for getting int
char charVal; // for skipping chars
while (true) {
while (! (std::cin >> intVal)) { // while no integer available
std::cin.clear(); // clear fail bit and
if (! (std::cin >> charVal)) { // skip the offending char.
return 0; // if no char left, end of file.
}
}
std::cout << intVal << '\n'; // print int and carry on
}
return 0;
}
A transcript follows:
pax> echo '{(314159,271828),(42,-1)}' | ./testprog
314159
271828
42
-1
I'm trying to read a variable length char* from the user input. I want to be able to specify the length of the string to read when the function is called;
char *get_char(char *message, unsigned int size) {
bool correct = false;
char *value = (char*)calloc(size+1, sizeof(char));
cout << message;
while(!correct) {
int control = scanf_s("%s", value);
if (control == 1)
correct = true;
else
cout << "Enter a correct value!" <<endl
<< message;
while(cin.get() != '\n');
}
return value;
}
So, upon running the program and trying to enter a string, I get a memory access violation, so I figured something has gone wrong when accessing the allocated space. My first idea was it went wrong because the size of the scanned char * is not specified within scanf(), but it doesn't work with correct length strings either. Even if I give the calloc a size of 1000 and try to enter one character, the program crashes.
What did I do wrong?
You have to specify the size of value to scanf_s:
int control = scanf_s("%s", value, size);
does the trick.
See the documentation of scanf_s for an example of how to use the function:
Unlike scanf and wscanf, scanf_s and wscanf_s require the buffer size to be specified for all input parameters of type c, C, s, S, or [. The buffer size is passed as an additional parameter immediately following the pointer to the buffer or variable.
I omit the rest of the MSDN description here because in the example they're providing, they use scanf instead of scanf_s what is quite irritating...