如何从文件的一列中找到最大和最小数目?然后显示与该数字关联的字符串? (不使用数组)


第1列:10 15 105 7 45
                                                                                                                                                       列2中的字符串:a b c d e

最佳答案

您只需要逐行读取文件,记住最小值和最大值以及与之相关的字符串,直到结束为止。

#include <fstream>
#include <limits>
#include <iostream>

void printMaxAndMin() {
  std::ifstream infile("file.txt");
  int curVal,
      maxVal = std::numeric_limits<int>::min(),
      minVal = std::numeric_limits<int>::max();
  std::string curStr, maxStr, minStr;

  while (infile >> curVal >> curStr) {
     maxStr = maxVal < curVal ? curStr : maxStr;
     maxVal = maxVal < curVal ? curVal : maxVal;

     minStr = minVal > curVal ? curStr : minStr;
     minVal = minVal > curVal ? curVal : minVal;
  }
  std::cout << "minimum: " << minVal << ", " << minStr << std::endl;
  std::cout << "maximum: " << maxVal << ", " << maxStr << std::endl;
}

10-06 08:40