在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++,但这里有一些东西可能不会在你所处的任何课程中运行,所以相应地进行调整:

#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>push_back(),那么很多代码都会消失,但如果你需要学习如何在底层做到这一点,那么这里就有指针和它们创建的所有混乱。

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

最新更新