首页 > 解决方案 > 在 while 循环结束时获取数字 -172492288 的窗口中的错误

问题描述

#include<iostream>
#include<fstream>

using namespace std;

int *elementShifter(int[], int);



int main()

{

    int SIZE = 50;
    int array[SIZE];
    ifstream infile("Gradelist.txt");
    if (!infile)
    {
        cout << "File not found" << endl;
        return -1;
    }

    int count = -1,data=0;

    while (!infile.eof())
    {
        count++;
        if (count < 0 || count > 50)
        return -1;
        else
        {
        infile >> array[count];

        }
        cout << array[count] << endl;
    }
    cout << endl;
    int *s=elementShifter(array, count);

    for (int i = 0; i <=count; i++)
    {
        cout << *s << endl;
        s++;

    }
    return 1;

}

int *elementShifter(int arr[], int size)

{

    int *newArr = new int[size + 1];
    newArr[0] = 0;

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

    {
    newArr[i+1]=arr[i];
    }

    return newArr;

}

我只是想不通为什么我在这里得到这个号码

标签: c++

解决方案


这被改写成稍微更惯用的 C++,但是这里的东西可能不会在你所学的任何课程中飞行,所以相应地适应:

#include<iostream>
#include<fstream>

// using namespace std; is a bad habit to get into, that prefix
// exists for an important reason: Code separation

// Tip: If you define before you reference a function in your code,
//      there is no need for a separate declaration.

// Note use of const on arguments that are not mutated
void unshift(int*& array, size_t& size, const int elem) {
  int *resized = new int[++size];

  // Insert at the start of the array
  resized[0] = elem;

  // Copy the remainder
  for (int i = 1; i < size; ++i) {
    resized[i] = array[i-1];
  }

  // Don't forget to release the old memory or you have a leak
  delete[] array;

  // Since the pointer is passed in as a reference, easy to swap it
  array = resized;
}

int main() {
  size_t size = 1; // size_t is often used for "size"-type args
  int *array = new int[size];

  std::ifstream infile("Gradelist.txt");

  if (!infile) {
    // Use std::cerr for errors.
    std::cerr << "File not found" << std::endl;

    return -1;
  }

  // infile evaluates as true so long as it has data to read.
  while (infile) {
    // You already have a count, it's "size"
    if (size> 50) {
      return -1;
    }

    int input;
    infile >> input;

    // This function takes mutable arguments, so they change via
    // references.
    unshift(array, size, input);
  }

  std::cout << std::endl;

  for (int i = 0; i < size; ++i) {
      std::cout << array[i] << std::endl;
  }

  // Take out the trash
  delete[] array;

  // Return zero on success, non-zero on failure.
  return 0;
}

当然,如果您可以使用std::vector<int>and ,很多这些代码都会消失push_back(),但是如果您需要学习如何在低级别执行此操作,那么您可以使用指针以及它们造成的所有混乱。

现代 C++ 的目标是避免使用指针,而是大量依赖标准库来帮助您。


推荐阅读