Wczytywanie liczb z pliku

0

Cześć, mam plik txt o takie treści:

Window 800 600
Close 1422 2321
Onthe 2211 3423

Jak najszybciej i najlepiej pobrać liczby te, które występują po słowie Close?

Zrobiłem to tak, że wczytałem za pomocą getline linię w pętli.
Potem w drugiej pętli sprawdzam po znaku czy txt[i] == (po kolei z tablicy: {'C', 'l', 'o', 's', 'e'})
Jeśli jest, to pobieram po kolei następne cyfry, które konwersuję na int, a następnie pierwszą cyfrę z liczby mnożę razy 100 albo 1000, zależy czy liczba jest 4 cyfrowa czy 3 cyfrowa, no a kolejne: *100, *10 itd. które potem sumuje.

Powiem, że może nie tyle jest to trudne, ale chciałbym zastosować coś lepszego.

3

uzyj do tego funkcji find, nie musisz sam sprawdzac. Korzystaj z narzedzi ktore sa dostepne

std::ifstream file("thefile.txt");
std::string line;
while (std::getline(file, line))
{
    if (file.find("Close") != string::npos)
    {
        std::istringstream inputstringstream(line);
        std::string text;
        int a, b;
        if (inputstringstream >> text >> a >> b) 
        { 
            // udalo sie wczytac, masz swoje liczby
        }
    }

}
1

Ewentualnie:

#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <utility>

using namespace std;

int main()
{
	ifstream file("file.txt");
	if(!file)
	{
		cout << "Unable to open file" << endl;
		return 1;
	}

	vector<pair<string, vector<int>>> data;
	for(string line; getline(file, line);)
	{
		istringstream iss(line);
		string name;
		iss >> name;
		vector<int> values;
		for(int temp_value; iss >> temp_value;)
		{
			values.push_back(temp_value);
		}
		data.push_back({ name, values });
	}

	/* wyswietlanie wszystkich elementów
	for(const auto &p : data)
	{
		cout << p.first << " ";
		for(const auto &v : p.second)
		{
			cout << "\'" << v << "\' ";
		}
		cout << endl;
	}
	*/

	// wyswietlanie tylko drugiego elementu
	cout << data[1].first << ": " << data[1].second[0] << " " <<  data[1].second[1];
}

Wtedy masz dostęp do wszystkiego.

1 użytkowników online, w tym zalogowanych: 0, gości: 1