![](/img/trans.png)
[英]Using getline() to read input (with spaces) from file into a structure
[英]How to input a string from a structure using getline?
我目前正在学习 C++ 数据结构基础知识,对字符串有一点疑问
我试图通过在主 function 中创建结构 object 的实例,从主 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;
}
但是在这里我在获取名称的 getline 中遇到错误。
mismatched types 'std::__cxx11::basic_string<_CharT, _Traits, _Alloc>' and 'std::string [50]' {aka 'std::__cxx11::basic_string<char> [50]'}
你能解释一下这里发生了什么吗? 谢谢
在字符串的情况下,memory 是动态分配的,更多的 memory 可以在运行时按需分配。 由于没有预分配 memory,因此没有浪费 memory。 所以绑定它会给出错误尝试 -
struct StudentData {
string name;
char rollNo[20];
int semester;
};
如果您仍想绑定输入,请尝试-
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;
}
当你到达getline(cin, s1.name);
, is 被编译为一个地址,该地址包含字符串对象数组的开头,因此计算机尝试将字符串写入 memory 中的字符串 class 的位置。
这是行不通的,因为分配给 memory 的不仅仅是一个 ascii 字符。
我相信您将string
与char []
数组混淆了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.