c++ - 如何从文本文件中的每个字符串中获取最大值 - C++

标签 c++ string

我有一个这样的文本文件;

1 13 330 323 18 1 40 410 413 45 1 28 381 347 16 1 16 230 261 27
2 6 208 218 8 2 24 253 277 21 2 13 223 244 14 2 10 177 185 6
3 0 12 1 1 3 20 417 416 18 3 23 322 320 23 3 5 21 23 4
4 1 7 18 2 4 11 149 138 11 4 11 120 116 10 4 2 27 24 3

我想取每个字符串的最大值。例如,在第一个字符串中,最高数字是 413,第二个字符串是 277。我有 40 行这样的行。我使用了这段代码,但我的代码无法正常工作——顺便说一句,我知道我做错了——它需要所有的数组,并且只需要 1 个最高值。我想我需要两个 for 循环来做这件事,但我已经犯了第一个错误,没有第二个 :) 也许这可以用“getline”函数来完成我真的不知道,但我需要你的帮助 atm...谢谢.

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <iomanip>
#include <fstream>
#include <string.h>

using std::cin;
using std::endl;
using std::cout;
using namespace std;

int main()
{
    int a[20][40]; 
    int x,y;  
    int sum = 0;
    FILE *myDataFile1;  
    ofstream myOutFile1;
    myOutFile1.open ("highestValues.txt"); 

    myDataFile1 = fopen("input.txt", "r");

    for ( x = 0; x < 20; x++)
    {
        for ( y = 0; y < 40; y++)
        {
            a[x][y] = 0;
        }
    }


    for (x = 0; x < 20; x++)
    {
        for ( y = 0; y < 40; y++)
        {
            fscanf(myDataFile1, "%d,", &a[x][y] );
        }
    }

    for (x = 0; x < 20; x++)
    {
        for ( y = 0; y < 40; y++)
        {
            sum = a[x][y];
        }
    }

    int maxValue = 0;


    for(x = 1; x < 20; x++)
    {
        for(y = 1; y < 40; y++)
        {
            if(a[x][y] > maxValue)
            {
                maxValue = a[x][y];
            }
        }
    }

    if (myOutFile1.is_open())
    {
        myOutFile1 << left << setw (5) << maxValue << endl;
    }
    cout << "The highest value is: " << maxValue << endl;
}

最佳答案

一种可能的解决方案:

std::fstream fs("test.txt");
std::string line;
while(std::getline(fs, line)) {
    std::stringstream str(line);
    std::istream_iterator<int> begin(str), end;
    std::vector<int> vec(begin, end)
    std::cout << *std::max_element(vec.begin(), vec.end()) << std::endl;
}

[编辑]

您的代码更像 C,C++ 版本(如您标记的问题)看起来像上面的代码。

您可以在 http://en.cppreference.com/w/ 上找到标题,为了使这个答案完整,我在下面添加它们:

#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <iterator>
#include <algorithm>
#include <fstream>

Here is a Live Example

关于c++ - 如何从文本文件中的每个字符串中获取最大值 - C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35992763/

相关文章:

c++ - Visual Studio 2010 默认属性表似乎在调试和发布配置下都有链接,这是怎么回事?

c# - 在字符串中搜索子字符串

java - 字符串数组和 BufferedReader

java - 将一个字符串转换为多个字符串

c++ - 关于冒号的简单C++语法问题

c++ - 构造函数的调用顺序

android - javah : Error: cannot access android. support.v7.app.AppCompatActivity?

c++ - 错误 LNK2001 : unresolved external symbol public: static class

c++ - 包含 <string> 时 xutility 出错

string - 如何将 PChar 的一部分提取到字符串中?