【发布时间】:2021-12-19 03:02:10
【问题描述】:
我正在编写读取文本文件的代码以显示数字,然后将它们从最小到最大排序我正在使用 C++ 进行编码。我遇到了两个问题,我得到的两个数字至少不是一个大的负数,而 622 不在列表中。我认为这是因为对数组的 null 重调
#include<iostream>
#include<cmath>
#include <iomanip>
#include <fstream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
const string INFILENAME = "100Numbers.txt"; //this find the name in the program foulder
ifstream inFile;
inFile.open(INFILENAME.c_str());//this open the file
const int NUMBER = 100;
int OneHundredNumber[NUMBER];
int NewOneHundredNumbe[NUMBER];
int Size = 0;
int FindSize;
int found = 0;
if (inFile.is_open())
{
while (!inFile.eof()) { //in the File when it hits -1 i what it to not input -1 and stop it
inFile >> OneHundredNumber[Size];//this is put the text in to the first arry
Size++;
}
printArray(NewOneHundredNumbe, Size, "");//note i this this is not need
loopfortheLoop(Size, NewOneHundredNumbe, OneHundredNumber, "The contents of the array are: ");
sort(OneHundredNumber, OneHundredNumber + Size);
loopfortheLoop(Size, NewOneHundredNumbe, OneHundredNumber, "The array has been sorted.");
for (int i = 0; i < Size; i++)
{
if (OneHundredNumber[i] == 234) {
found++;
}
}
cout << endl << "The number ""234"", was found " << found << " times.";
inFile.close(); // CLose input file
}
else { //Error message
cerr << "Can't find input file " << INFILENAME << endl << "Pleace add it to the Progeran Files or cheack if the name of the text file is 100Numbers.txt";
}
return 0;
}
100Numbers.txt
137 354 328 263 120 36 124 138 175 365 180 170 179 144 45 379 97 31 357 274 142 314 3 327 321 137 122 331 308 366 352 71 363 14 85 266 287 80 91 370 117 374 57 204 224 148 268 280 292 363 399 388 325 234 230 331 89 390 212 55 297 622 151 266 272 63 331 21 250 141 154 15 61 234 23 143 99 389 196 29 361 180 288 47 62 50 347 180 234 334 130 230 184 214 177 154 129 391 234 -1
【问题讨论】:
-
代码太多了,不太可能有人会花时间检查你的整个程序来发现问题。您应该阅读minimal reproducible example 并提供更好的代码示例。
-
我注意到一个问题:我认为您应该继续阅读,直到
inFile.eof()为真,但直到最后一次读取值为-1。 -
既然你说这段代码有一个错误——你有没有在调试器中单步调试过这段代码?这通常是下一步要采取的措施。
-
首先,您的输入循环很危险,因为它不进行任何边界测试,例如
Size < NUMBER。您的addElementToArray函数似乎负责增加数组大小,但这是 按值 传递给函数的,因此调用者永远不会看到这种变化。一般来说,对于琐碎和常见的操作,有太多的代码拆分为函数。它增加了不必要的复杂性和出错的空间。最重要的是,我的口味太多了。如果您正在构建 API,那么这种风格的文档可能是可以接受的。
标签: c++ visual-c++ c++17