Home > Software design >  How can I create a variable based in the user's input?
How can I create a variable based in the user's input?

Time:11-23

I am trying to program a school bulletin (I'm sorry if that's not the right word, what I meant with "bulletin" is the thing were are the grades of each student. English isn't my 1° language) and I want to ask the user the name of the student and then create a

int student_name;

so I don't need to create a 1000 of

int student_1
int student_2

and then just use cin <<. So, how can I do that? I hope my question was easy to understand. Thanks!

CodePudding user response:

#include <iostream>
#include <map>
#include <string>
void createStudent(std::map<string, int>& input)
{
    std::string name;
    int grade;
    for(int i=0; i<1000;   i)
    {
        std::cin>>name>>grade;
        input.insert(std::pair<string, int>(name, grade));
    }
    return;
}
void showContentMap(std::map<string, int>& input)
{
    for(int i=0; i<input.size();   i)
    {
        std::cout<<input[i].first<<" : "<<input[i].second<<std::endl;
    }
    return;
}
int main()
{
    std::map<string, int> students;
    createStudent(students);
    showContentMap(students);
    return 0;
}

Explanation:

  1. An execution of the command-function createStudent() assigns into the parameter students their identifiers such as name and grade. It is known that the quantity of students is 1000.
  2. The command-function showContentMap() demonstrates the content of the parameter students.
  3. The main properties of a student are name and grade. These properties will be assigned into the parameter map<string, int> students.

CodePudding user response:

Since you want to create a system that allows you to add and remove student names, it is best to use something like std::vector<std::string> studentNames;. Every time that you want to append a new student name, you can use studentNames.pushBack("John Doe");.

Remember to #include <vector> it at the top of your code.

  • Related