簡體   English   中英

如何使用 getline 從結構中輸入字符串?

[英]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 字符。

我相信您將stringchar []數組混淆了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM