Search code examples
c++arraysstructure

How to divide the input taken from user in two parts and assign them to two different arrays in C++?


If we take the input from user by asking them, like below:

cout << "Enter your course code and course name: ";

Now if the user enters CS201 Introduction to Programming, how can I only assign the code part, i.e. CS201 to an array, let's say;

char courseCode[10];

And how can I assign the name part in the array, let's say:

char courseName[50];

I want to do this to 5 students, using the structure defined below:

struct student
{
    char courseName[50];
    char courseCode[10];
};

student stu[5];

Solution

  • I solved my problem using the cin.getline() functions to get the string in token pointer and then used strchr(char [], cahr) of <string> header file to separate the current string from the place where the first white space comes. Then I copied both separated strings into my desired elements of my structure using strcpy() function.