简体   繁体   English

如何使用 getline 从结构中输入字符串?

[英]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我目前正在学习 C++ 数据结构基础知识,对字符串有一点疑问

I am trying to input a string value from the main function by creating an instance of a structure object in the main function.我试图通过在主 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;
}

But here I am getting error in getline for name.但是在这里我在获取名称的 getline 中遇到错误。

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.在字符串的情况下,memory 是动态分配的,更多的 memory 可以在运行时按需分配。 As no memory is preallocated, no memory is wasted.由于没有预分配 memory,因此没有浪费 memory。 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);当你到达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. , is 被编译为一个地址,该地址包含字符串对象数组的开头,因此计算机尝试将字符串写入 memory 中的字符串 class 的位置。

This will not work because the memory is allocated to not just hold an ascii character.这是行不通的,因为分配给 memory 的不仅仅是一个 ascii 字符。

I believe you are confusing string with char [] array.我相信您将stringchar []数组混淆了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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