将数字从文本文件读取到数组中

Reading numbers from textfile into array

本文关键字:数组 读取 文件 数字 文本      更新时间:2023-10-16

我一直在玩这个,但我一无所获。 我正在尝试将整数列表从 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
    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};
        }
    }
}

}

要从 istream 中读取单个整数,您可以这样做

int a;
inputFile >> a;

这就是您在 while 循环中所做的。while 很好,因为对于流(在文件)中的每个整数,您将执行 will 的块

inputFile >> a一次读取一个整数。 如果放入测试中(如果/同时),真值将回答"是否已读取该值?

我不明白你试图对你做什么number变量。由于没有由您初始化,它就像它的值0一样,最终使 foor 循环无法运行

如果你想准确地读取100整数,你可以这样做

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;
}

你没有读a到你的numbers中,把你的代码改成这样:

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
        }
    }
}

如果您正在循环访问文件,则每次都会用新数字覆盖数组。这可能不是您打算做的。您可能想用 100 个不同的号码填写 100 个位置?在这种情况下,请使用以下代码:

if (!inputFile){
    //error handling
    cout << "File can't be read!";
}
else{
    int i = 0;
    while (inputFile >> a){  // Whilst an integer is available to read
        DataFile[i] = a;   // Fill a location with it.
        i++;               // increment index pointer
    }
}