C++字符串对象、数组和结构

C++ string objects, arrays, and structs

本文关键字:结构 数组 字符串 对象 C++      更新时间:2023-10-16

嗨,我想知道是否可以在代码问题上获得一些帮助。我正在尝试使用结构输入数据并将其存储在数组中。当每个输入只有一个单词时,它似乎有效,但如果我尝试输入多个单词,我会得到无限循环。

例如,对于歌曲标题,如果我输入:"快速"它有效,但如果我输入"快速汽车",我会得到无限循环。

我还包含一个打印数组数据库的选项,但是如果我没有填充所有 20 个位置,我会得到未使用点的随机输出。我希望它,如果我输入少于 20 首歌曲,它只会打印我输入的内容。提前谢谢你。

#include <iostream>
#include <string>
#include <cctype>
#include <fstream>
#include <sstream>
using namespace std;
void ShowMenu();
struct AFile
{
    string artist;
    string title;
    int length;
    string type;
};
int main()
{
    const int numOfFiles = 20;
    AFile songs[numOfFiles];
    int index = 0, num, songNum = 0;
    int menuSelection;
    bool quit = false;
    while (!quit)
    {
        ShowMenu();
        cin >> menuSelection;
        switch (menuSelection)
        {
            //input data
        case 1:
            cout << "Enter the Song number to be input: ";
            cin >> num;
            if (num == (index + 1))
            {
                songNum = (num - 1);
                cout << "Enter the Artist of song # " << num << ": ";
                cin >> songs[songNum].artist;
                cout << "Enter the Title of song # " << num << ": ";
                cin >> songs[songNum].title;
                cout << "Enter the length in seconds of song # " << num << ": ";
                cin >> songs[songNum].length;
                cout << "Enter either mp3 or wav of song # " << num << ": ";
                cin >> songs[songNum].type;
                ++index;
                cout << "You have " << index << " songs entered into the database.";
                break;
            }
            else
                cout << "Invalid input.";
            break;
            //printout data
        case 2:
            int i;
            cout << "Displaying Database:" << endl;
            cout << endl;
            for (i = 0; i < index; i++)
            {
                cout << songs[i].artist << "-";
                cout << songs[i].title << "-";
                cout << songs[i].length << "s.";
                cout << songs[i].type << endl;
            }

            break;
            //edit data
        case 3:


            break;
            //end program
        case 4:
            quit = true;
            break;
        default:
            cout << "Bad entry please try again " << endl;
            break;
        }
    }
    system("pause");
    return 0;
}

void ShowMenu()
{
    cout << endl;
    cout << "What would you like to do? " << endl;
    cout << "1) input data" << endl;
    cout << "2) print out all data" << endl;
    cout << "3) edit data" << endl;
    cout << "4) end program" << endl;
}

使用带有空格的字符串的正确方法是使用 getline

改变这个-

cout << "Enter the Title of song # " << num << ": ";
                cin >> songs[songNum].title; 

对此——

getline(std::cin,songs[songNum].title);