CrazyEngineers
  • string/char input

    Neohacker

    Neohacker

    @neohacker-FP4O5e
    Updated: Oct 27, 2024
    Views: 1.2K
    I want to take input for name of a student ...
    when i do char name[20]; and take input with cin>>name; it prints only upto 1st space like if i type "jimmy green" then it will print only "jimmy"

    when i take string name; and try to input with getline(cin,name) then it prints the next line before the input like this

    here is my code :

    #include<iostream>
    #include<string>
    using namespace std;

    struct student {
    string name;
    int age;
    };

    int main() {
    int n;
    cout<<"Enter the total no. of students : ";
    cin>>n;

    student s1[n];

    for(int i=0;i<n;i++) {
    cout<<"Student "<<i+1<<" : \n\t"<<"Name : ";
    getline(cin,s1.name);
    cout<<"Age : ";
    cin>>s1.age;
    }
    }


    And here is the output :


    Enter the total no. of students : 3
    Student 1 :
    Name : Age :


    You see that the "Age" is appearing before entering the "name" ... so how can i fix this problem ??????
    0
    Replies
Howdy guest!
Dear guest, you must be logged-in to participate on CrazyEngineers. We would love to have you as a member of our community. Consider creating an account or login.
Replies
  • Neohacker

    MemberSep 26, 2014

    nvm 😛 i added cin.ignore() after cin and now it's working fine .
    Are you sure? This action cannot be undone.
    Cancel
  • ManojKiran Eda

    MemberOct 4, 2014

    Another alternative is to use flushall() function after the scanning of an interger.
    Are you sure? This action cannot be undone.
    Cancel
Home Channels Search Login Register