无法在数组中添加元素
c++ Not able to add an element in the array
我对c++还是个新手。我试图在数组中添加另一个元素。该函数应该在addEntry函数完成后更改数组和数组中的项数,但是它没有这样做。如果我使用display函数来显示数组,则只显示原始数组。请帮助。
#include<iostream>
#include<string>
using namespace std;
const int MAXSIZE = 10; // total size of array
void display(string[], int);
void addEntry(string[], int&);
int main()
{
string name[MAXSIZE] = {"raj","casey","tom","phil"};
int numEntries = 4; // number of elements in the array
string choice; // the user choice to add an element or display or exit
cout<<numEntries<<" names were read in."<<endl;
do
{
cout<<endl<<"Enter menu choice (display, add, quit): ";
getline(cin,choice);
if (choice == "display")
{
display(name, numEntries);
cout<<endl;
}
else if (choice == "add")
{
addEntry(name, numEntries);
cout<<endl;
}
else
{
cout<<"bye"<<endl;
}
} while (choice!="quit");
system ("pause");
return 0;
}
void display(string name[], int numEntries)
{
for (int i = 0; i < numEntries; i++)
{
cout<<name[i]<<endl;
}
return;
}
void addEntry(string name[], int& numEntries)
{
if (numEntries<MAXSIZE-1)
{
numEntries++;
cout<<"Enter name of the person to add: ";
getline(cin,name[numEntries]);
cout << "Entry added.";
return;
}
else
{
cout<<"There is not enough space is in the array to add a new entry!";
return;
}
}
getline(cin,name[numEntries]);
numEntries
是数组中有效条目的数量。name[numEntries]
是紧跟在最后一个有效条目之后的元素。使用name[numEntries-1]
或者更好的是,使用std::vector
而不是C数组,毕竟,您是用c++编写的。
您的程序工作,您只是在addEntry中指向数组中的错误位置。请记住,c++中的数组是基于0的,尝试在数组中插入元素后增加numEntries的值,例如:
void addEntry(string name[], int& numEntries)
{
if (numEntries<MAXSIZE)
{
cout<<"Enter name of the person to add: ";
getline(cin,name[numEntries++]);
cout << "Entry added.";
return;
}
else
{
cout<<"There is not enough space is in the array to add a new entry!";
return;
}
}
代码中的错误在以下几行:
numEntries++;
cout<<"Enter name of the person to add: ";
getline(cin,name[numEntries]);
调用getline
后,需要增加numEntries
。用途:
cout<<"Enter name of the person to add: ";
if ( getline(cin,name[numEntries]) )
{
// Increment only if getline was successful.
numEntries++;
}
相关文章:
- 有没有办法向这个向量添加元素?
- 如何在提升间进程中构建具有给定计数的向量并向其添加元素
- 如何在 Arduino 字符串的开头添加元素.类似于 JS unshift();
- C++向数组添加元素并调整数组大小
- 我无法向 c++ 添加元素
- BST 不添加元素
- 调整数组大小并添加元素 C++
- 向向量添加元素
- 如何在不使用标准算法的情况下在排序向量中添加 c 元素?
- 双链接列表添加元素不起作用,不知何故它总是保持为空
- 当我向 vector<int *> 添加元素时,我遇到了一些问题
- 动态地添加元素
- 静态2D数组,添加元素
- 在一个类中向向量添加元素不适用于其他类
- 在数组中添加元素将不接受类似的元素
- STD :: MAP-使用下标操作员与插入方法添加元素
- 动态数组添加元素而不创建结构变量/对象
- 以下向 c++ 向量添加元素的方法有什么区别
- 如何在 std::map 中添加元素自己进行分配
- C++在向量中添加元素的双精度