c ++无法在数组中添加元素

时间:2015-08-13 19:07:30

标签: c++ arrays function

我对c ++很新。我想在数组中添加另一个元素。 addEntry函数完成后,该函数应该更改数组和数组中的项数,但它不会。如果我使用display函数显示数组,则只显示原始数组。请帮忙。

Method invocation tv.setText(mContext.getText(R.string.intro) + "\n\n")' may 
produce java.lang.NullPointerException' less... (Ctrl+F1) This inspection 
analyzes method control and data flow to report possible conditions that are 
always true or false, expressions whose value is statically proven to be 
constant, and situations that can lead to nullability contract violations. 
Variables, method parameters and return values marked as @Nullable or 
@NotNull are treated as nullable (or not-null, respectively) and used during 
the analysis to check nullability contracts, e.g. report possible munpoin 
terException errors. 
More complex contracts can be defined using @contract annotation, for     
example: 
@Contract("_, null -> null") — method returns null if its second argument is 
null @Contract("_, null -> null; _, !null -> !null") — method returns null 
if its second argument is null and not-null otherwise @Contract("true -> 
fail") —atypical  assertFalse method which throws an exception if true is 
passed to it 
The inspection can be configured to use custom @Nullable @NotNull 
annotations (by default the ones from annotations.jar will be used) 

3 个答案:

答案 0 :(得分:1)

getline(cin,name[numEntries]);

numEntries是数组中有效条目的数量。 name[numEntries]是跟随上一个有效条目的元素。使用name[numEntries-1]

或者甚至更好,使用std::vector而不是C数组,毕竟,你是用C ++编写的。

答案 1 :(得分:0)

您的代码中的错误如下:

  numEntries++;
  cout<<"Enter name of the person to add: ";
  getline(cin,name[numEntries]);

调用numEntries后,您需要增加getline。使用:

  cout<<"Enter name of the person to add: ";
  if ( getline(cin,name[numEntries]) )
  {
     // Increment only if getline was successful.
     numEntries++;
  }

答案 2 :(得分:0)

您的程序有效,您只是在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;
    }
}