改变数组的大小值

  • 本文关键字:数组 改变 c++ arrays
  • 更新时间 :
  • 英文 :


制作一个程序,从文件中读取整数并创建一个数组,我已经完成了这部分,但是我正试图弄清楚如何根据文件中有多少整数来改变SIZE值。这个文件有15个整数,但另一个文件可能有更多,这个数组不会接受所有的整数。

using namespace std;
const int SIZE = 15;
int intArray[SIZE];
void readData(istream& inFile) {
for (int i = 0; i < SIZE; i++){
inFile >> intArray[i];
cout << intArray[i] << " ";
}
}
int main() {
ifstream inFile;
string inFileName = "intValues.txt";
inFile.open(inFileName.c_str());

int value, count = 0;
while(inFile >> value){
count += 1;
}

cout << count;
readData(inFile);
return 0;
}

正如你所看到的,我有一个while循环来计算文件中int型的数量,但是当我把它赋值给size值时,我遇到了许多不同的问题。

固定大小的数组不能调整大小,句号。如果你需要一个数组,它的大小可以在运行时改变,使用std::vector代替。

更重要的是,您读取整个文件只是为了计算整数的数量,然后尝试从前一个循环结束的位置读取值。您不需要将ifstream查找回文件的开头,因此您可以重新读取已读过的内容。

试试这样写:

#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
int main() {
string inFileName = "intValues.txt";
ifstream inFile(inFileName.c_str());
int value, count = 0;
while (inFile >> value){
++count;
}

cout << count;
std::vector<int> intArray;
intArray.reserve(count);
inFile.seekg(0);
while (inFile >> value){
intArray.push_back(value);
cout << value << " ";
}
// use intArray as needed...
return 0;
}

或者,甚至不需要计算整数,只需让std::vector根据需要增长,例如:

#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
int main() {
string inFileName = "intValues.txt";
ifstream inFile(inFileName.c_str());
vector<int> intArray;
int value;
while (inFile >> value){
intArray.push_back(value);
cout << value << " ";
}
// use intArray as needed...
// you an get the count from intArray.size()
return 0;
}