简体   繁体   English

从文本文件中读取 100 个数字并找到最小值和最大值

[英]Read 100 Numbers from a text file and find minimum and maximum values

Created a text file and put in 100 random numbers.创建一个文本文件并输入 100 个随机数。 Trying to read the file.试图读取文件。 The text file looks like:文本文件如下所示:

 27 12 37 53 83 2
    #include<iostream>
    #include<fstream>

    using namespace std;

    int main()
    {
       int i,min,max;
       ifstream fin;
       fin.open("DATA.txt",ios::in);
       fin>>i;
       max=i;
       min=i;

       while(fin>>i)
       {
           if(i>max)
               max=i;
           if(i<min)
               min=i;
       }
       cout<<max<<" "<<min;
       fin.close();
   }

I originally tried to do it using read function but it gives garbage values.我最初尝试使用 read 函数来做到这一点,但它给出了垃圾值。 Why does this code not work?为什么这段代码不起作用?

    #include<iostream>
    #include<fstream>

    using namespace std;

    int main()
    {
       int i,min,max;
       ifstream fin;
       fin.open("DATA.txt",ios::in);
       fin.read((char*)&i,sizeof(i));
       max=i;
       min=i;
       while(fin)
       {
           fin.read((char*)&i,sizeof(i));
           if(i>max)
               max=i;
           if(i<min)
               min=i;
       }
       cout<<max<<" "<<min;
       fin.close();
   }

You can do the following:您可以执行以下操作:

    #include<iostream>
    #include<fstream>

    using namespace std;

    int main()
    {
       int i,min,max;
       ifstream fin;
       fin.open("DATA.txt",ios::in);
       max=INT_MIN; // least possible int value
       min=INT_MAX; // largest possible int value

       while(fin>>i)// reads till the end of file
       {
           if(i>max)
               max=i;
           if(i<min)
               min=i;
       }
       cout<<max<<" "<<min;
       fin.close();
   }

Assuming sizeof(int) == 4 (which is true on most platforms), the first time you execute the line假设sizeof(int) == 4 (在大多数平台上都是如此),第一次执行该行时

fin.read((char*)&i,sizeof(i));

it will read the first 4 bytes (=characters) of the file, which are "27 1" .它将读取文件的前 4 个字节(=字符),即"27 1" Assuming the file is ASCII encoded, these 4 bytes have the following values:假设文件是ASCII编码的,这 4 个字节具有以下值:

  1. 50 ( ASCII code for the digit '2' ) 50 (数字'2' ASCII 码
  2. 55 (ASCII code for the digit '7' ) 55 (数字'7' ASCII 码)
  3. 32 (ASCII code for the character ' ' ) 32 (字符' ' ASCII 码)
  4. 49 (ASCII code for the digit '1' ) 49 (数字'1' ASCII 码)

Assuming that you are on a little-endian platform, the mentioned byte values will result in an int with the value 824,194,866 .假设您使用的是little-endian平台,上述字节值将生成一个值为824,194,866int

This is what happens when you read your text file as binary data, which is obviously not what you want.当您将文本文件作为二进制数据读取时会发生这种情况,这显然不是您想要的。 What you want is to read the file as text.您想要的是将文件作为文本读取。 You want to read digits until you encounter a non-digit character, interpret these digits as a number, and then write that number to an int variable.您想读取数字直到遇到非数字字符,将这些数字解释为数字,然后将该数字写入int变量。 This is exactly what the << stream extraction operator does in the expression fin>>i that you are using.这正是您使用的表达式fin>>i中的<<流提取运算符所做的。

Therefore, your second piece of code is fundamentally incorrect, because it interprets the file data as binary, whereas your first piece of code is fundamentally correct, as it interprets the file data as text.因此,您的第二段代码从根本上是不正确的,因为它将文件数据解释为二进制文件,而您的第一段代码从根本上是正确的,因为它将文件数据解释为文本。

The question is already answered.问题已经回答了。 However, we should not go without an additional solution that shows the "more modern" C++ approach.然而,我们不应该没有一个额外的解决方案来展示“更现代”的 C++ 方法。

And therefore I offer the below answer for your kind evaluation.因此,我为您的友好评价提供以下答案。

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

int main() {
    // Open file and check, if it could be opened. (using C++17 features)
    if (std::ifstream dataFileStream{ "data.txt" }; dataFileStream) {

        // Read all values and get iterator to min and max element
        const auto [min, max] = std::minmax_element(std::istream_iterator<int>(dataFileStream), {});
        
        // Show result to user
        std::cout << "Min: " << *min << " \t Max: " << *max << '\n';
    }
    else {
        // File could not be opened. Show error
        std::cerr << "\nError: Could not open source file\n\n";
    }
    return 0;
}

This is a short and compact solution.这是一个简短而紧凑的解决方案。 Without any loop.没有任何循环。

Maybe somebody will be inspired by it.也许有人会受到启发。

All answers are given.给出了所有答案。 Your part one is totally fine and the reason for the problem with part 2 has been explained very could by Andreas Wenzel +1.您的第一部分完全没问题,Andreas Wenzel +1 已经很好地解释了第二部分出现问题的原因。

Last but not least I will show an (one of many possible) additional solution, using more modern C++ elements.最后但并非最不重要的一点是,我将展示一个(许多可能的)附加解决方案,使用更现代的 C++ 元素。

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

int main() {
    // Open file and check, if it could be opened
    if (std::ifstream dataFileStream{ "data.txt" }; dataFileStream) {

        // Read all values and get iterator to min and max element
        const auto [min, max] = std::minmax_element(std::istream_iterator<int>(dataFileStream), {});
        
        // Show result to user
        std::cout << "Min: " << *min << " \t Max: " << *max << '\n';
    }
    else {
        // File could not be opened. Show error
        std::cerr << "\nError: Could not open source file\n\n";
    }
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM