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

advertisements

basically if we take the input from user by asking him, like below:

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

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

char courseCode[10];

And how can I assign the name part in the array, lets 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];

Kindly help me, I can't figure out how can I divide the input in two parts and assign them in two different arrays which are present in the structure I defined above. Thanks in advanced.


It's actually kind of simple once you remember that the input operator >> stops on white-space, and also know about the std::getline function.

Then you can do something like

std::string courseCode;
std::string courseName;

std::cin >> courseCode;
std::getline(std::cin, courseName);

Note that I use std::string for the strings instead of arrays. This is what you really should use. If you're not allowed (by your teacher or something) and must use arrays, then you can't use std::getline but instead have to use std::istream::getline instead.