C++字符串对象、数组和结构
C++ string objects, arrays, and structs
嗨,我想知道是否可以在代码问题上获得一些帮助。我正在尝试使用结构输入数据并将其存储在数组中。当每个输入只有一个单词时,它似乎有效,但如果我尝试输入多个单词,我会得到无限循环。
例如,对于歌曲标题,如果我输入:"快速"它有效,但如果我输入"快速汽车",我会得到无限循环。
我还包含一个打印数组数据库的选项,但是如果我没有填充所有 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);
相关文章:
- C++将文本文件中的数据读取到结构数组中
- JSON转换为nlohmann JSON-lib中的结构数组
- 需要帮助将结构数组传递给函数
- 在 64 位边界上对齐C++结构数组?
- 带有枚举方向/类型的气泡排序结构数组
- 在C++中访问结构数组中的数据
- 从指向结构数组的指针中提取元素
- 如何制作一个地图,其中的值是C++中的结构数组
- 如何在函数中显示结构数组
- 包含作为成员C++函数的结构数组
- 如何修复函数中的 fstream 文件输入以将正确的信息存储在结构数组中?
- std::transform 将一个结构数组复制到另一个结构数组
- 将非托管结构数组封送到托管数组
- 显示结构数组
- 结构数组中所有类似字段的总和
- 结构数组的构造函数错误,错误消息:没有构造函数实例与参数列表匹配
- 在 glsl opengl 中将嵌套结构数组作为统一传递
- 使用初始化列表填充C++中的多维结构数组时出现问题
- 如何将字符串字符与结构数组进行比较?
- C++结构数组