Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/spring-mvc/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C++;文件输出时程序崩溃_C++ - Fatal编程技术网

C++ C++;文件输出时程序崩溃

C++ C++;文件输出时程序崩溃,c++,C++,我正在尝试编写一个程序,它获取一个名称列表,然后将其输出到.txt文件 这是我的代码: void setNames() // Set method that takes a series of names. { nameTags = new char*[numberOfNames]; for (int i=0; i<=numberOfNames; i++) { nameTags[i] = new char[128]; cout << "Input i

我正在尝试编写一个程序,它获取一个名称列表,然后将其输出到
.txt
文件

这是我的代码:

void setNames() // Set method that takes a series of names.
{
  nameTags = new char*[numberOfNames];
  for (int i=0; i<=numberOfNames; i++)
  {
    nameTags[i] = new char[128];
    cout << "Input information for name " << i << ": " << "\n";
    cin.getline(namesSet, sizeof(namesSet));
    strcpy(nameTags[i], namesSet);
  }
}

ostream& operator<< (ostream& ostr, const Names& names) // <<operator
{
  ostr << "#############################" << endl;
  ostr << names.getAuthor();
  ostr << names.getNumberOfNames();
  for(int i=0; i<=names.numberOfNames; i++)
  {
    ostr << names.nameTags [i] << "\n";
  }
  return ostr;
}

我对C++很陌生,如果有人能帮我解决问题,我会非常感激。我花了几个小时试图修复它。

问题在于声明:

for (int i=0; i<=numberOfNames; i++)

用于(int i=0;i使用
std::string
std::vector
而不是动态分配的字符数组*如果
getline
失败,则缓冲区将充满垃圾,这可能导致problem@MattMcNabb我想可能是
getline
导致了这个bug。我已经声明
nameset
char名称集[100]
+1.写入超过缓冲区结尾的内容肯定可以解释这一点。我只是尝试了一下……没有什么区别。正如我提到的,我认为这是输出文件stream@user4167396:尽管如此,这是一个错误,导致未定义的行为。您可能还有其他错误。@user4167396:如果修复此错误不能解决问题,我认为您没有显示的代码中有错误。例如,我怀疑
sizeof(nameset)
,因为指针上的
sizeof
是一个常见的错误。但是您没有显示
nameset
@fredrarson
nameset
的声明被声明为
char nameset[100]
for (int i=0; i<=numberOfNames; i++)
for (int i=0; i < numberOfNames; i++)
for(int i=0; i < names.numberOfNames; i++)