How to take input to an array with unknown number of elements?
std::vector<int>
is what you need. Think of it as an array of dynamic size.
you can add elements to a vector by using .push_back()
see https://en.cppreference.com/w/cpp/container/vector
How to take input to an array with unknown number of elements? ( I don't wanna use std::vector )
Once you do
int arr[n];
the size of the array is decided, once and for all. There's no way you can change it.
On the other hand, you can dynamically allocate memory to which a pointer points to.
int * arr;
arr = new int[n];
// now you can use this arr just like the other one
If you need, later, to change the size of the memory to which arr
points, you can deallocate and reallocate as needed.
delete [] arr;
arr = new int[m];
// probably there's a more idiomatic way of doing this, but this is really too
// much C for me to care about this details...
Obviously you need to think about how you can take care of copying the values to another temporary array to avoid loosing them during the deallocation-reallocation process.
All this madness, however, is not necessary. std::vector
takes care of all of that for you. You don't want to use it? Fine, but you're not writing C++ then. Full stop.
Add user input to array of unknown size
regarding:
int main(void)
{
int score;
// start count for size of array
int count = - 1;
do
{
score = get_int("Score: ");
// add one to the count for each score
count++;
}
while (score != 0);
// now the size of the array is defined by how many times the user has typed.
int scores[count];
for (int i = 0; i < count; i++)
{
// how do I add each score to the array???
}
}
this does not compile and contains several logic errors
it is missing the statements: #include <cs50.h>
and#include <stdio.h>
regarding:
int score;
// start count for size of array
int count = - 1;
do
{
score = get_int("Score: ");
// add one to the count for each score
count++;
}
while (score != 0);
This only defines a single variable: score
and each time through the loop that single variable is overlayed. Also, the first time through the loop, the counter: count
will be incremented to 0, not 1
on each following time through the loop, the variable score
will be overlayed (I.E. all prior values entered by the user will be lost)
suggest using dynamic memory. Note: to use dynamic memory, will need the header file: stdlib.h
for the prototypes: malloc()
and free()
. Suggest:
#include <cs50.h>
#include <stdio.h>
#include <stdlib.h>
int main( void )
{
// pointer to array of scores
int * score = NULL;
// start count for size of array
int count = 0;
while( 1 )
{
int score = get_int("Score: ");
if( score != 0 )
{ // then user has entered another score to put into array
count++;
int * temp = realloc( scores, count * sizeof( int ) )
if( ! temp )
{ // realloc failed
// output error info to `stderr`
// note: `perror()` from `stdio.h`
perror( "realloc failed" );
// cleanup
free( scores );
// `exit()` and `EXIT_FAILURE` from `stdlib.h`
exit( EXIT_FAILURE );
}
// implied else, 'realloc()' successful, so update the target pointer
scores = temp;
// insert the new score into the array
scores[ count ] = score;
}
else
{ // user entered 0 so exit the loop
break;
}
}
note: before exiting the program, pass scores
to free()
so no memory leak.
How do I take an unknown amount of numbers in a single line as input and assign each number to a variable?
Using a linked list is not necessary for this, so a simple solution would be to use a dynamically allocated array to store the elements. Use the following code:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int n;
printf("How many number? ");
scanf("%d", &n);
int *arr = malloc(sizeof *arr * n);
printf("Enter numbers: ");
for (int i = 0; i < n; i++)
scanf("%d", &arr[i]);
printf("The numbers you entered are: ");
for (int i = 0; i < n; i++)
printf(i == (n - 1) ? "%d" : "%d ", arr[i]);
printf("\n");
return 0;
}
Java - Taking user input to create an unknown number of class objects/arrays/arrayLists
Well please consider that grades are related to student and limited to always 4.
Therefore I suggest to implement a dynamic list of a class student with enclosed array of grades.
Example:
import java.util.Scanner;
import java.util.ArrayList;
public class TestGrades {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<Student> studlist = new ArrayList<Student>();
boolean loop = true;
while (loop) {
System.out.println(" Please Enter Student Name");
String scanedline = scanner.nextLine();
if(scanedline.equals("C"))
{
break;
}
else
{
studlist.add(new Student(scanedline));
}
System.out.println("Please enter Student Grade");
for (int j = 0; j < 4; j++)
{
System.out.print(""+j+">");
Double scannedgrade = Double.parseDouble(scanner.nextLine());
studlist.get(studlist.size() - 1).grade[j]=scannedgrade;
}
System.out.println(studlist.get(studlist.size() - 1).name);
for (int j = 0; j < 4; j++)
System.out.print(studlist.get(studlist.size() - 1).grade[j] + " ");
System.out.println("");
}
}
private static class Student
{
String name;
Double [] grade;
Student (String s)
{
this.name = s;
grade = new Double[4];
}
}
}
c++11 way of returning an array of unknown number of elements
Trailing return type should do the job:
struct DataBinding {
static constexpr auto getRawBindings()
-> decltype(
asConstArray(
DEF_BINDING(int, stateProp, stateParam), //BindingInfo constexpr object
DEF_BINDING(float, areaProp, areaParam) //BindingInfo constexpr object
//(...)
)
)
{
return asConstArray(
DEF_BINDING(int, stateProp, stateParam), //BindingInfo constexpr object
DEF_BINDING(float, areaProp, areaParam) //BindingInfo constexpr object
//(...)
);
}
};
To avoid the repetition, MACRO might help:
#define RETURN(Expr) decltype(Expr) { return Expr; }
and then
struct DataBinding {
static constexpr auto getRawBindings()
-> RETURN(
asConstArray(
DEF_BINDING(int, stateProp, stateParam), //BindingInfo constexpr object
DEF_BINDING(float, areaProp, areaParam) //BindingInfo constexpr object
//(...)
)
)
};
Related Topics
How Come a Non-Const Reference Cannot Bind to a Temporary Object
Store Hex Value as String (Arduino Project)
How to Peek At the Next Element in a Range-For Loop
Vector Converted All Negative Values to Zero
How to Convert String to Ip Address and Vice Versa
Checking If All Elements of a Vector Are Equal in C++
How to Install (V142) Build Tools in Visual Studio
C++ - Initializing Variables in Header VS With Constructor
While Writting Unittests for a Function, Should I Mock the Internal Function Calls Made
Most Efficient Way of Copying a Raw Byte Array into an Empty Byte Vector
C++ Convert String to Hexadecimal and Vice Versa
Carry Over Data Without Using for Loop
Escape Sequence \F - Form Feed - What Exactly Is It
Vscode C++ Task.Json Include Path and Libraries
How to Properly Add Include Directories With Cmake
Define Preprocessor Macro Through Cmake