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
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.