1

I want to take students name and id and then print them. How can I do it? I used a string array "name[20]" for storing name and an int array "id[20]" for storing id. I used getline() for name array and cin for id array inside same for loop. But problem is it is not taking id values. My code is

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

int main(){
    int n, i;
    string name[20];
    int id[20];
    for ( i=0; i<=20; i++){

        getline(cin, name[i]);
        cin>>id[i];
    }
    for ( i=0; i<=20; i++)
        cout<<name[i]<<"    "<<id[i]<<"\n";
}
Onindo Ani
  • 11
  • 1
  • 2
  • 1
    How is the input formatted? If the name and id are on one line, then `getline` will read both, and you'll have to extract the id from that. If they're on separate lines, then `>>` won't read the end-of-line character(s), so you'll have to ignore that before calling `getline`. – Mike Seymour Mar 13 '15 at 14:14
  • 2
    Not exactly related to what you have posted, but this: `i<=20` will fail. Try replacing both instances with `i<20` – npinti Mar 13 '15 at 14:14
  • Read this: http://stackoverflow.com/questions/21567291/why-does-stdgetline-skip-input-after-a-formatted-extraction – NathanOliver Mar 13 '15 at 14:14

0 Answers0