C ++从文件中读取整数并保存到数组中 [英] C++ read integers from file and save into array

查看:42
本文介绍了C ++从文件中读取整数并保存到数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个仅从文本文件中读取整数的程序.我想创建一个读取整数并将其存储在数组中的函数,以便以后可以使用该数组通过冒泡排序对它们进行排序.到目前为止,这是我所拥有的,但是我得到的输出是一些随机的-803234 .... number:

I'm making a program that reads only integers from text file. I want to make a function that reads integers and stores them in an array so I can use that array later to sort them with bubble sort. This is what I have so far but the output I get is some random -803234.... number :

void read(int A[max], int& numbers) { 
    ifstream file("ints.txt");
    if (file.is_open()) {
        file >> numbers;

        for (int i = 0; i < numbers; i++) {
            cout << "numbers: " << A[i] << endl;
        }
        file.close();
    }
    cout << "numbers in array: " << A[numbers] << endl;
}

推荐答案

在任何时候都不将数字存储在数组中:

You don't store the numbers in the array at any point:

void read(int A[max], int& numbers) { 
    ifstream file("ints.txt");
    if (file.is_open()) {
        file >> numbers;

        for (int i = 0; i < numbers; i++) {
            // you're printing A[i] but you haven't stored
            // anything there.
            cout << "numbers: " << A[i] << endl;

我假设 numbers 是文件中的条目数,并且您打算以与读取 numbers 相同的方式读取值,但要读入A [i].

I assume that numbers is the number of entries in the file and that you intended to read the values the same way you read numbers but into A[i].

cin >> A[i];

代码的最后一部分还将尝试打印到数组的最后一项之外:

The last part of your code also tries to print beyond the last entry of the array:

cout << "numbers in array: " << A[numbers] << endl;

请记住,C ++数组是基于0的,所以 A [numbers] 是* numbers + 1 * th项.

Remember, C++ arrays are 0 based, so A[numbers] is the *numbers + 1*th entry.

这篇关于C ++从文件中读取整数并保存到数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆