-2

I was making a multi linked list program, but my function for enrolling to a course is not working. When I use cin, it takes only course name and doesn't take course instructor name as input, and when I use getline() function, it doesn't accept input of both of them. Why it is behaving like this?

#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <iostream> //for cin and cout
using namespace std;

struct course
{
    string cName;
    string cInst;
    int cNo;
    struct course* next;
    struct student* start;
} *Cstart = NULL;

struct student
{
    string sName;
    int sNo;
    int Class;
    struct student* link;
};

void EnrollCourse()
{
    struct course* temp;
    temp = (struct course*) malloc(sizeof(struct course));
    printf("Enter your Course No :");
    scanf("%d", &temp->cNo);
    printf("\nEnter your Course Name: "); //getline didn't work on it
    getline(cin, temp->cName);
    cout << temp->cName;
    printf("\nEnter your Instructor Name: ");
    getline(cin, temp->cInst);
    cout << temp->cInst;
    temp->next = NULL;
    temp->start = NULL;
    if (Cstart == NULL)
    {
        Cstart = temp;
    }
    else
    {
        struct course* curr = Cstart;
        while (curr->next != NULL)
        {
            curr = curr->next;
        }
        curr->next=temp;
    }
}

int main()
{
    EnrollCourse();
    EnrollCourse();
    EnrollCourse();
    EnrollCourse();
    return 0;
}
Remy Lebeau
  • 454,445
  • 28
  • 366
  • 620
  • 3
    Why are you mixing c and c++ input methods?? – πάντα ῥεῖ May 25 '21 at 16:26
  • I just wanted to use string and and not char variableName[n].Since printf and scanf doesn't work on string that is why I used Cin ...can u plz highlight my mistake and tell me about the better approach .I am new to C++ language. – Areeba Junaid May 25 '21 at 16:33
  • @AreebaJunaid You are likely encountering a variation of [Why does std::getline() skip input after a formatted extraction?](https://stackoverflow.com/questions/21567291/), only with `scanf()` instead of `operator>>`, but the result is the same. Also, like πάνταῥεῖ said, this code is very much C and not C++. They are very different languages. Don't mix them unnecessarily. This code can and should be done entirely in C++. For instance, using `operator>>` instead of `scanf()`, `operator< – Remy Lebeau May 25 '21 at 16:44
  • U shld uz constructor & init list w/ yr struct. – Thomas Matthews May 25 '21 at 16:44
  • `temp=(struct course*)malloc(sizeof(struct course));` doesn't propert construct the `cName` and `cInst` members. This leaves those objects in UB land. When you assigned to `cName` for example, the compiler is expected a properly constructed `cName` to target ; you're not giving that. If dynamic allocation is really required you should be using `new` and `delete`, not `malloc` and `free` in C++ (and frankly, you often don't need those either). – WhozCraig May 25 '21 at 16:50

0 Answers0