无法在数组中添加元素

c++ Not able to add an element in the array

本文关键字:添加 元素 数组      更新时间:2023-10-16

我对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++;
  }