簡體   English   中英

在 C++ 中,如何將字符串輸入到結構的 char 數組中?

[英]In C++ how can I input a string into a char array of struct?

我是計算機科學的初學者,我遇到了一個問題,我在任何地方都找不到解決方案。 當我嘗試使用cin.get();輸入字符串時cin.get();

#include <iostream>
#include <string>
#include <cstring>

using namespace std;

int SIZE = 0;

struct Books {
    float isbn;
    string author;
    string Bname;
};

void funAddb(Books book[], int);

int main()
{

    int choose;
    Books book[SIZE];
    int n;
    do {
        cout << " WELCOME \n ENTER (2) to return a borrowed book:";
        cin >> choose;
        switch (choose) {
        case 2:
            funAddb(book, SIZE);
            break;
        }
        cout << endl
             << "If you want to stop please enter (0):" << endl;
        cin >> n;
    } while (n != 0);
    return 0;
}

void funAddb(Books b[], int SIZE)
{
    cout << endl
         << "Please enter the book name:" << endl;
    cin.ignore(100, '\n');
    getline(cin, b[SIZE].Bname);
    cout << endl
         << "Please enter the ISBN:" << endl;
    cin >> b[SIZE].isbn;
    cout << endl
         << "Please enter the author name:" << endl;
    cin.ignore(100, '\n');
    getline(cin, b[SIZE].author);
    SIZE++;
}

大小應該是可變的而不是固定的,我發現的解決方案建議我將數組的大小更改為 100,但我不知道這樣做的目的是什么

我首先要說的是,下次您應該發布一個最小的、可重復的示例,因為不清楚您的問題是什么,以及您從哪里獲得“解決方案”。
有人告訴您放置固定大小以允許將大量元素放入您的數組中,但由於兩個主要原因,這是一種糟糕的方法:

  • 如你所說,大小是不可改變的。 所以如果你達到 100 本書,你就不能再添加了
  • 如果您沒有完全填滿您的陣列,這將極大地浪費您的 PC 內存

為了改變 C++ 數組的大小,您可以使用指針來初始化“動態”數組,語法為Books *mybooks = new Books[SIZE] ,盡管它仍然不是最佳選擇,因為指針保存在計算機 RAM 的,這基本上意味着您必須自己處理大小和內存,計算機不會像靜態數組一樣為您處理。

隨着你繼續你的編程生涯,你會發現人們創造了更快的算法、容器和其他東西。 標准模板的向量類在您的情況下非常方便,其語法非常簡單:

int SIZE=0;
struct Books{
 float isbn;
 string author;
 string Bname;
};
vector<Books> mybooks; //create empty vector
vector<Books> mybooks2(SIZE); //create vector with dimension

Books newBook; //initialize new book
mybooks.push_back(newBook) //add your book to the container

我還建議使用類而不是結構; 雖然一開始它們更難理解,但結果證明它們更有用! 希望能幫助到你

暫無
暫無

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

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