Problems with C/C++ Struct Array

Asked

Viewed 30 times

1

I’m trying to make a program that reads a string and int and stores its values in one struct and then print it on the screen, I’m still learning, forgive me if it’s a very obvious mistake. Code:

#include<iostream>

using namespace std;

struct teste {
    int num;
    char str[16];
};

int main(){
    struct teste var[3];
    int i;
    
    for(i = 0; i < 3; i++){
        cin >> var[i].num;
        cin.getline(var[i].str, 16);
        //fgets(var[i].str, 15, stdin);
    }
    
    int j;
    
    for(j = 0; j < 3; j++){
        cout << endl << var[j].num << endl;
        cout << var[j].str << endl;
    }
    
    return 0;

}

1 answer

2


Getting a '\n' in the buffer after you read the whole... As the next reading is of a whole line, it ends up getting in the way. You can do the following to fix:

for(i = 0; i < 3; i++){
        cin >> var[i].num;
        cin.ignore(); //ADICIONA ESSA LINHA AQUI
        cin.getline(var[i].str, 16);
        //fgets(var[i].str, 15, stdin);
    }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.