How to Read and Print String with c++ space?

Asked

Viewed 261 times

0

I even managed to make my program read the String (name of a person) with space in C++. However, when printing only returns the first name of the person as in my program below.

//Write a program that registers the name, enrollment and two grades of several students. Then print the enrollment, the name and average of each of them.

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


struct cadastro{
  char nome[100];
  int matricula;
  float nota1,nota2;
  float media;
};

int main() {

 
  int i, qtdeAlunos=3;
  cadastro a1[3];

    for(i = 0; i < 3; i++){
      cout<<"\nInsira seu nome: ";
      //scanf ("%[^\n]%*c", a1[i].nome);
      cin>>a1[i].nome;
      //getline( cin, a1[i].nome );
      //cin.ignore();
      cin.ignore(100,'\n');
      cout<<"\nInsira sua matricula: ";
      cin>>a1[i].matricula;
      cout<<"\nInsira sua primeira nota: ";
      cin>>a1[i].nota1;
      cout<<"\nInsira sua segunda nota: ";
      cin>>a1[i].nota2;
    } 
    for(i = 0; i < 3; i++){
      cout<<"\nNome: " << a1[i].nome;
      cout<<"\nMatricula: " << a1[i].matricula;
      cout<< "\nSua media é: " <<(a1[i].nota1+a1[i].nota2)/2;
    }
     
}

1 answer

0

To read and print Strings in C++, you can use the function getline, an example of use (based on your case) would be:

// Lendo Strings
#include <iostream>
#include <string>
using namespace std;

struct cadastro{ char nome[100]; int matricula; float nota1,nota2; float media; };

int main() {

  cadastro a1[3];

  cout<<"\nInsira seu nome: ";
  cin.getline( a1[0].nome,sizeof(a1[0].nome) );
  cout<< a1[0].nome;


}

This code is available for testing here.

Browser other questions tagged

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