从文件中读取数字并将其存储在数组c ++中时出现问题

问题描述 投票:-1回答:2

我的程序的目标是最终将填充了数字(由用户选择)的文件读入数组并输出最小值和最大值。但是,我无法让我的代码在文件中输出正确数量的输入,我想将其用作数组的大小。

我现在的代码是

#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>

using namespace std;

int main(){
    string fileName;
    int count(0);
    cout << "Enter input file name: ";
    cin >> fileName;
    ifstream in_file;
    in_file.open(fileName);
    if(in_file.is_open()){
        in_file >> count;
        }
    cout << "The number of entries is " << count;
    int arrayNumbers[count];    
    for (int i = 0; i < count; ++i){
        in_file >> arrayNumbers[i];
        cout << arrayNumbers[i] << endl;
    }
    in_file.close();
}

我有一个名为tester.txt的文本文件与我的.cpp文件位于同一目录中,但它只有9个条目(1-9在单独的行上)但是当我输入计数时,它表示计数为12.我见过在其他问题,如我的使用

in_file >> count;

计算一个文件中有多少个数字,但我不明白这是我第一次从文件中读取的内容。我试图读取的文件中包含以下内容

1
2
3
4
5
6
7
8
9

我还没有开始问题的第二部分,找到最小值和最大值,但是我只是要对数组进行排序然后显示arrayNumber [0]和arrayNumber [count-1]以显示最小值和最大值,但首先我需要知道基于输入文件制作数组的大小。

c++ arrays ifstream
2个回答
2
投票

但我不明白这是做什么的

它将你的ifstream的第一个数字读入count

对于必须按预期工作的代码,您需要将总数量附加到输入文件的开头,以便您的文件看起来像这样。

9
1
2
3
4
5
6
7
8
9

0
投票

感谢所有的建议,我设法让它按预期工作。我将在下面发布我的代码。

#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include <algorithm>
#include <iterator>

using namespace std;

string fileName;
int num, counter = 0;

int main(){
    cout << "Enter input file name: ";
    cin >> fileName;
    ifstream in_file;
    in_file.open(fileName);

    while(in_file >> num){
        counter = counter+1;
    }
    in_file.clear();                    //clear the eof flag after reaching end of file
    in_file.seekg (0, ios::beg);        //go back to the start of the file to read
    int arrayNumbers[counter];          
    for (int i = 0; i < counter; ++i){
        in_file >> arrayNumbers[i];
    }
    in_file.close();
    sort(arrayNumbers, arrayNumbers+counter);
    cout << "Min: " << arrayNumbers[0] << endl 
         << "Max: " << arrayNumbers[counter-1];
}
© www.soinside.com 2019 - 2024. All rights reserved.