结构中带空格的字符串

问题描述 投票:0回答:1

我需要输入将包含空格的字符串Dept_nameHod,但是cin >>不允许这样做,并且使用getline会给出错误的参数错误。输入另一个数组中带空格的字符串的最简单方法是什么?我很困惑,因为我使用的是结构数组,但是我了解到getline也要求字符串也要采用数组形式。请耐心等待,因为我是编程新手,谢谢:)

#include <string>
#include <sstream>
#include<stdio.h>
using namespace std;
struct department
{
    string Dept_name;
    string Dept_id;
    int No_of_students;
    int NumberOfFacultyMembers;
    string Hod;
};


void readlist(department *v1, int v2);
void updatelist(department *v1, int v2);

int main()
{
    int choice;
    department list[5];

    cout<<"Welcome to Department Section\n";
    cout<<"Enter your choice\n";
    cout<<"Press 1 to take information of Department\n";
    cout<<"Press 2 to Update information of any Department\n";

    cin>>choice;

    if (choice==1)

    {
        readlist(list,5);
    }

    else if (choice==2)

    {
        updatelist(list,5);
    }
    cout<<"Enter your choice\n";
    cout<<"Press 1 to take information of Department\n";
    cout<<"Press 2 to Update information of any Department\n";
    cin>>choice;

    if (choice==1)

    {
        readlist(list,5);
    }

    else if (choice==2)

    {
        updatelist(list,5);
    }

    return 0;
}
void readlist(department *v1, int v2)
{
    for (int i=0; i<v2; i++)
    {
        cout<<"\n\n********** Information of department "<<i+1<<" **********";
        cout<<"\nEnter department name: ";
        cin>>(v1->Dept_name);
        cout<<"\nEnter department ID: ";
        cin>>(v1->Dept_id);
        cout<<"\nEnter number of students: ";
        cin>>(v1->No_of_students);
        cout<<"\nEnter number of faculty members: ";
        cin>>(v1->NumberOfFacultyMembers);
        cout<<"\nEnter HoD's name': ";
        cin>>(v1->Hod);
        v1++;
    }
}
void updatelist(department *v1, int v2)
{
    string id;
    cout<<"Enter Department ID\n";
    cin>>id;
    for (int i=0; i<v2; i++)
    {
        if ((v1->Dept_id)==id)
         {
            cout<<"Enter new number of faculty members\n";
            cin>>(v1->NumberOfFacultyMembers);
            cout<<(v1->Dept_name)<<" now has "<<(v1->NumberOfFacultyMembers)<<" faculty members\n";
         }

        v1++;
    }

}

c++ arrays string structure
1个回答
0
投票

如何使用std :: getline:的简单示例]

struct department
{
    std::string Dept_name;
    std::string Dept_id;
    int No_of_students;
    int NumberOfFacultyMembers;
    std::string Hod;
};

int main()
{
    department dep;

    std::cout << "Write some text:\n";

    std::getline(std::cin, dep.Hod);

    std::cout << "You wrote: \"" << dep.Hod << "\".\n";
}

使用:

Write some text:
Rayscary is a scary ray?
You wrote: "Rayscary is a scary ray?".
© www.soinside.com 2019 - 2024. All rights reserved.