简体   繁体   中英

How to input a string from a structure using getline?

Im currently going through C++ Basics in data structure and have a small doubt regarding strings

I am trying to input a string value from the main function by creating an instance of a structure object in the main function.

#include<iostream>
#include<sstream>
#include<string>

using namespace std;

struct StudentData {
  string name[50];
  char rollNo[20];
  int semester;
};

int main() {
  struct StudentData s1;
  cout<<"Enter the name, Roll.No and Semester of the student:"<<endl;
  getline(cin, s1.name);
  cin>>s1.rollNo>>s1.semester;
  cout<<endl<<"Details of the student"<<endl;
  cout<<"Name: "<<s1.name<<endl;
  cout<<"Roll.No: "<<s1.rollNo<<endl;
  cout<<"Semester: "<<s1.semester<<endl;
  return 0;
}

But here I am getting error in getline for name.

mismatched types 'std::__cxx11::basic_string<_CharT, _Traits, _Alloc>' and 'std::string [50]' {aka 'std::__cxx11::basic_string<char> [50]'}

Could you please explain what is happening here? Thank you

In the case of strings, memory is allocated dynamically, More memory can be allocated at run time on demand. As no memory is preallocated, no memory is wasted. So bonding it will give an error try-

struct StudentData {
string name;
char rollNo[20];
int semester;
};

if you want to still bond the input try-

using namespace std;
  struct StudentData {
  string name;
  char rollNo[20];
  int semester;
 };

  int main() {
    struct StudentData s1;
    cout<<"Enter the name, Roll.No and Semester of the student:"<<endl;
    getline(cin, s1.name);

    while(s1.name.size()>50){
        string word;
        cout<<"Invalid!"<<endl;
        cout<<"enter-name again"<<endl;
        getline(cin, word);
        s1.name = word;
        cout<<s1.name.size()<<endl;
    }
    cin>>s1.rollNo>>s1.semester;
    cout<<endl<<"Details of the student"<<endl;
    cout<<"Name: "<<s1.name<<endl;
    cout<<"Roll.No: "<<s1.rollNo<<endl;
    cout<<"Semester: "<<s1.semester<<endl;
    return 0;
  }

When you get to getline(cin, s1.name); , is is compiled to an address which contains the start of an array of string objects so the computer tries to write a string of characters to the location of a String class in memory.

This will not work because the memory is allocated to not just hold an ascii character.

I believe you are confusing string with char [] array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM