Khubaib Khawar
Khubaib Khawar

Reputation: 311

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];

Upvotes: 0

Views: 299

Answers (3)

Khubaib Khawar
Khubaib Khawar

Reputation: 311

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.

Upvotes: 0

Krash
Krash

Reputation: 2307

Store the input in a single string say x

Now on x perform linear search for the first whitespace and split the string about the first whitespace. Store the two resultant strings in your struct.

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409472

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.

Upvotes: 3

Related Questions