读取数字的文本文件,并存储在C++的整数数组中

Read a text file of numbers and store into an array of integers in C++

本文关键字:C++ 整数 数组 存储 数字 文本 文件 读取      更新时间:2023-10-16

我需要从文本文件中存储一个整数数组,但我找不到我需要为它做什么。我想我有代码设置的基础,但我认为我需要将元素转换为整数或其他东西?

我的

输出是我的列表:

500201018-5152234-1

但是我的"排序"列表最终是-1,以及一系列大的负数。我将其排除在阵列有问题。

#include <iostream>
#include <fstream>
using namespace std;
int main() 
{
    int array1[30];
    int counter=0,n=0;
    fstream datafile;
    void bubbleSort(int list[], int length);
    void selectionSort(int list[], int length);
    /////////////
    datafile.open("data.txt");
    if (!datafile.is_open())
    {
        cout << "Failure to open." << endl;
        return 0;
    }
    while (!datafile.eof()) {
        datafile >> array1[counter];
        n++;
        cout << array1[counter] << endl;
    }
    datafile.close();
    //////////////////////////////
    //bubbleSort(array1, n);
    //selectionSort(array1, n);
    for (int i = 0; i < n; i++)
        cout << array1[i] << ", ";
    system("pause");
    return 0;
}

永远不要使用 eof() ,因为它会导致错误的程序。原因请参阅 https://stackoverflow.com/a/5837670。

while (n < 30 && datafile >> array1[n]) {
    cout << array1[n] << endl;
    n++;
}
{
    int excess;
    if (datafile >> excess) {
        cerr << "error: data file too largen";
        return;
    }
}

这样,n在程序结束时是正确的。

你的代码都很好,除了:

 while (!datafile.eof()) {
        datafile >> array1[counter];
        n++;
        cout << array1[counter] << endl;
    }

它应该是:

while (!datafile.eof()) {
        datafile >> array1[n];
        if ( datafile.fail() ) break; 
        cout << array1[n] << endl;
        n++;
    }

只需要一个索引变量(n)来解析/存储到一维数组中。一段时间后n++的增量语句应始终是最后一个,以便您正在处理当前元素而不是下一个元素。

法典:

#include <iostream>
#include <fstream>
using namespace std;
int main() 
{
    int array1[30];
    int n=0;
    fstream datafile;
    void bubbleSort(int list[], int length);
    void selectionSort(int list[], int length);
    /////////////
    datafile.open("data.txt");
    if (!datafile.is_open())
    {
        cout << "Failure to open." << endl;
        return 0;
    }
    while (!datafile.eof()) {
        datafile >> array1[n];
        if (datafile.fail()) break;
        cout << array1[n] << endl;
        n++;
    }
    datafile.close();
    for (int i = 0; i < n; i++)
        cout << array1[i] << ", ";
    system("pause");
    return 0;
}