is it possible to declare a two dimensional array that stores a name and grade
because the data type of name is string and the data type of grade is int
so im having trouble on how i will declare it
please help me thanks
An array only stores one type and making it 2-d won't help because the 2 dimensions refer to the index numbers (locations) not the data itself. However you can do what you are thinking of by creating a class or struct with your two attributes of name and grade. ie encapsulate your data.
#include <iostream>
#include <string>
#include <stdexcept>
int main()
{
constint n = 10; // Number of students
std::string student[n];
int grades[n];
int counter = 0;
// Get names and grades
std::cout << "Enter a name and a grade for " +
std::to_string( n ) + " students (q=quit): ";
for ( int i = 0; i < n; i++, counter++ ) {
// Get name
std::cout << std::endl << "Name: ";
std::string str;
if ( !std::getline( std::cin, str ) || str == "q" ) {
break;
}
student[i] = str;
// Get grade
std::cout << "Grade: ";
if ( !std::getline( std::cin, str ) || str == "q" ) {
break;
}
// Exit from the program if user wrote non-number character
try {
int grade = std::stoi( str );
grades[i] = grade;
} catch ( const std::logic_error &e ) {
std::cerr << "Error: incorrect grade." << std::endl;
return 1;
}
}
// Show names and grades
std::cout << std::endl << "You wrote:" << std::endl;
for ( int i = 0; i < counter; i++ ) {
std::cout << "Name: " << student[i] << std::endl;
std::cout << "Grade: " << grades[i] << std::endl;
std::cout << std::endl;
}
return 0;
}
Program output:
Enter a name and a grade for 10 students (q=quit):
Name: Ivan
Grade: 5
Name: Marry
Grade: 5
Name: q
You wrote:
Name: Ivan
Grade: 5
Name: Marry
Grade: 5
@Observer
it must be a multidimensional array
and the value of the elements inside the array is based on how many times the user inputs the grade and name of the student;
and i also need to display all the names and grade inputted by the user
i have no problem in getting the name and grade my problem is how i will display it because everytime i run the program it gives me garbage
You cannot have a multidimensional array containing data of different types.
Howeverm you can cast int to string and store it near name I do not know why would you want this abomination