我正在做一个家庭作业,要求我从另一个文件中提取数据并将其放入一个数组中,然后创建另一个具有相同数据的数组,但新数组的大小加倍,并用 0 填充其余空间。
我能够将数据拉入两个数组,但我不知道如何用 array2 上的 0 填充数组的其余部分。
我也在努力理解如何使用指针,所以我以我知道的方式制作了这个程序,所以我有一些东西然后尝试翻译它,除非现在有人能够帮助我翻译它,但我的主要重点是填0
#include <iostream>
#include <fstream>
using namespace std;
int SIZE = 10;
void pullData(int array[], int SIZE){
string inFileName = "data.txt";
ifstream inFile;
inFile.open(inFileName.c_str());
if(inFile.is_open()){
for(int counter = 0; counter < SIZE; counter++){
inFile >> array[counter];
}
}
}
void doubledArray(int array[], int SIZE){
string inFileName = "data.txt";
ifstream inFile;
inFile.open(inFileName.c_str());
if(inFile.is_open()){
for(int counter = 0; counter < SIZE; counter++){
inFile >> array[counter];
}
}
SIZE = SIZE * 2;
for(int counter = 10; counter < SIZE; counter++){
array[counter] = 0;
}
}
void arrayPrint(int array[], int SIZE){
for(int counter = 0; counter < SIZE; counter++){
cout << array[counter] << "\n";
}
}
int main(){
int array2[SIZE];
int array[SIZE];
pullData(array, SIZE);
arrayPrint(array, SIZE);
cout << endl << endl;
doubledArray(array2, SIZE);
arrayPrint(array2, SIZE);
return 0;
}
/*
I get:
1
2
3
4
5
6
7
8
9
10
1
2
3
4
5
6
7
8
9
10
When I want:
1
2
3
4
5
6
7
8
9
10
1
2
3
4
5
6
7
8
9
10
0
0
0
0
0
0
0
0
0
0
*/
你必须使用常量表达式(在索引中)来声明一个数组。不能用变量声明。除了。调用函数时,括号内的调用是参数。函数定义中括号中的是仅存在于函数范围内的变量。您将不得不通过引用调用该函数,但要解释这个话题有点长。看看这段代码的变化,反思一下。
#include <iostream>
#include <fstream>
using namespace std;
const int SIZE = 10;
const int SIZE2 = SIZE * 2;
void pullData(int array[], int S){
string inFileName = "data.txt";
ifstream inFile;
inFile.open(inFileName.c_str());
if(inFile.is_open()){
for(int counter = 0; counter < S; counter++){
inFile >> array[counter];
}
}
}
void doubledArray(int array[], int S){
string inFileName = "data.txt";
ifstream inFile;
inFile.open(inFileName.c_str());
if(inFile.is_open()){
for(int counter = 0; counter < S; counter++){
inFile >> array[counter];
}
}
for(int counter = 10; counter < S; counter++){
array[counter] = 0;
}
}
void arrayPrint(int array[], int S){
for(int counter = 0; counter < S; counter++){
cout << array[counter] << "\n";
}
}
int main(){
int array2[SIZE];
int array[SIZE2];
pullData(array, SIZE);
arrayPrint(array, SIZE);
cout << endl << endl;
doubledArray(array2, SIZE2);
arrayPrint(array2, SIZE2);
return 0;
}
我试过:
数据.txt 0 1个 2个 3个 4个 5个 6个 7 8个 9