【问题标题】:Strings with spaces in structures结构中带有空格的字符串
【发布时间】:2020-09-23 03:56:07
【问题描述】:

我需要输入包含空格的字符串 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++;
    }

}

【问题讨论】:

  • 最简单的方法是使用std::getline 并传递正确的参数。

标签: c++ arrays string structure


【解决方案1】:

如何使用 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?".

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-09
    • 2015-07-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多