C++ 将数字从文本文件读入数组
我一直在玩这个,但我什么也没得到。我试图从txt文件中将整数列表读入数组(1,2,3,…)。我知道将要读取的整数数量,100,但我似乎无法填充数组。每次我运行代码本身时,它只存储所有100个整数的值0。有什么想法吗C++ 将数字从文本文件读入数组,c++,arrays,C++,Arrays,我一直在玩这个,但我什么也没得到。我试图从txt文件中将整数列表读入数组(1,2,3,…)。我知道将要读取的整数数量,100,但我似乎无法填充数组。每次我运行代码本身时,它只存储所有100个整数的值0。有什么想法吗 //Reads the data from the text file void readData(){ ifstream inputFile; inputFile.open("data.txt"); if (!inputFile){ //error handling
//Reads the data from the text file
void readData(){
ifstream inputFile;
inputFile.open("data.txt");
if (!inputFile){
//error handling
cout << "File can't be read!";
}
else{
int a;
while (inputFile >> a){
int numbers;
//Should loop through entire file, adding the index to the array
for(int i=0; i<numbers; i++){
DataFromFile [i] = {numbers};
}
}
}
//从文本文件读取数据
void readData(){
ifstream输入文件;
open(“data.txt”);
如果(!inputFile){
//错误处理
cout>a){
整数;
//应该循环遍历整个文件,将索引添加到数组中
对于(int i=0;i您没有将a
读入您的数字
,请将代码更改为:
if (!inputFile){
//error handling
cout << "File can't be read!";
}
else{
int a;
while (inputFile >> a){
//Should loop through entire file, adding the index to the array
for(int i=0; i<a; i++){
DataFromFile [i] = a; // fill array
}
}
}
if(!inputFile){
//错误处理
cout>a){
//应该循环遍历整个文件,将索引添加到数组中
对于(int i=0;i a){//,同时可以读取整数
数据文件[i]=a;//用它填充一个位置。
i++;//增量索引指针
}
}
要从istream中读取单个整数,可以执行以下操作
int a;
inputFile >> a;
这就是你在while循环中所做的。
while在sens中很好,对于流(文件中)中的每个整数,您将执行will块
此inputFile>>a
一次读取一个整数。如果进行测试(if/while),真值将回答问题“值是否已读取?”
我不明白你想用number
变量做什么。因为它不是由你初始化的,所以它的值是0
,这使得foor循环无法运行
如果您想准确读取100
整数,您可以这样做
int *array = new int[100];
for (int i=0; i<100; ++i)
inputFile >> array[i];
谢谢你的回答。第一种方法成功了,现在我的程序启动并运行了:)
int *array = new int[100];
for (int i=0; i<100; ++i)
inputFile >> array[i];
int value;
int counter = 0;
while(inputFile >> value && checksanity(counter))
{
array[counter++] = value;
}