C ++: получить числа между двумя строковыми разделителями и значениями после извлечения целого числа из строки с использованием stringstream - PullRequest
0 голосов
/ 18 января 2020
    ```
    #include <iostream>
    #include <string>
    #include <sstream>
    #include <vector>
    #include <fstream>

    using namespace std;


    bool findCurrentNumber (int currentNumber, int foundNumber) 
    {
        if (currentNumber == foundNumber) 
        {
            return true;
        }
        return false;
    }


    int main()
    {

        ifstream inputFile;
        inputFile.open("C:\\Projects\\data.txt");
        if (!inputFile) 
        {
            cerr << "Error reading file "; 
        }
        else 
        {
        int searchCurrentNumber;
        cout << "Please type in the number you are looking for: ";
        cin >> searchCurrentNumber;

        bool foundRelevantSection = false;
        string delimiter = "energy";
        size_t pos = 0;
        string token;
        string line;


        while (getline(inputFile, line)) 
        {
             while ((pos = line.find(delimiter)) != string::npos) 
             {
                    token = line.substr(0, pos);
                    //check the found token
                    //cout << token << endl;
                    line.erase(0, pos + delimiter.length());
                    stringstream ss;     
                    //store the whole string into stringstream
                    ss << token; 
                    string temp; 
                    int found; 
                    while (!ss.eof()) 
                    { 
                    //extract the word by word from stream
                    ss >> temp; 
                    //Check the given word is integer or not
                    if (stringstream(temp) >> found) 
                    cout << "Number found: " << found << " " << endl;; 
                    //no space at the end of string
                    temp = ""; 
                    }
                    if (findCurrentNumber (searchCurrentNumber, found) == true)
                    {
                        while (getline (inputFile, line)) 
                        {
                        if (foundRelevantSection) 
                            {
                                //if no matches were found, the function returns "string::npos"
                                if(line.find("total") != string::npos) 
                                {
                                    //relevant section ends now
                                    foundRelevantSection = false;   
                                }
                                else    
                                {
                                cout << line << endl;
                                }
                            }
                            else 
                            {
                                if (line.find("point") != string::npos )
                                {
                                    foundRelevantSection = true;
                                }
                            }

                        }
                    }               
                    else 
                    {
                    cout << "The number is not equal on this line compared to what is typed in!" << endl;
                    }
              }                     
        } //closes the while-loop
    } //closes the if/else-statement

    inputFile.close();

        return 0;
    }
```

Привет всем,

Я хотел бы проанализировать входной файл в следующем формате:

point     152 # energy  # 0.5
152 152 152 152 152 152
152 152 152 152 152 152
total  0.011  0.049  0.035 

point     153 # energy  # 1.5
153 153 153 153 153 153
153 153 153 153 153 153
total  0.015  0.050  0.040

Код принимает введенное пользователем целое число и сравнивает его с числом, извлеченным, например, из строки «точка 152 # энергия». Если пользователь вводит число «152», код должен давать следующие цифры:

output: 
152 152 152 152 152 152
152 152 152 152 152 152

К сожалению, мой код возвращает с точностью до наоборот, если введено число 152 или если число 153 Введенные значения не возвращаются.

Может ли кто-нибудь помочь мне и сказать, что я делаю неправильно? Я благодарен за любую подсказку!

Заранее спасибо!

С наилучшими пожеланиями,

DaveS

Ответы [ 2 ]

1 голос
/ 18 января 2020

Я проверил ваш код, хотя это не так просто, но я смог понять, чего вы пытаетесь достичь, по крайней мере. В любом случае, вот мой собственный вклад в ваш вопрос. Я надеюсь, что это поможет вам или, по крайней мере, даст вам лучшее представление о решении

#include <iostream>
#include <fstream>
#include <regex>

int main()
{
    using namespace std;

    ifstream inputFile;

    inputFile.open("sample.dat");

    if (!inputFile)
    {
        cerr << "Error reading file ";
    }
    else
    {
        int searchCurrentNumber;
        bool foundRelevantSection = false;

        cout << "Please type in the number you are looking for: ";
        cin >> searchCurrentNumber;

        //while we are still having data to read
        std::string currentLine;
        while (std::getline(inputFile, currentLine))
        {
            //remove the top and bottom section of the log 
            if((currentLine.find("point") == string::npos) && (currentLine.find("total") == string::npos ))
            {
                //now all the numbers are in the middle then search for the number
                size_t pos = currentLine.find(std::to_string(searchCurrentNumber));
                if(pos!= string::npos){
                    //we found the number so we are in the section hopefully
                    string line;
                    while (std::getline(inputFile, line)) 
                        {
                        if (foundRelevantSection) 
                            {
                                //if no matches were found, the function returns "string::npos"
                                if(line.find("total") != string::npos) 
                                {
                                    //relevant section ends now
                                    foundRelevantSection = false;   
                                }
                                else    
                                {
                                cout << line << endl;
                                }
                            }
                            else 
                            {
                                if (line.find("point") != string::npos )
                                {
                                    foundRelevantSection = true;
                                }
                            }

                        }
                }
            }
        }
    }

    return 0;
}
1 голос
/ 18 января 2020

Исправлено исправление второй ошибки в конце.

Вы должны работать над улучшением отладчика, я нашел вашу проблему с одним:

while (!ss.eof()) 
    { 
    //extract the word by word from stream
    ss >> temp; 
    //Check the given word is integer or not
    if (stringstream(temp) >> found) 
         cout << "Number found: " << found << " " << endl;; 
    //no space at the end of string
    temp = ""; 
    }

нет Остановимся на поиске 152 в «точке 152 #», но переходим к процессу #, который превращает найденное в 0.

Этот код с разрывом исправляет эту часть:

while (!ss.eof()) 
    { 
    //extract the word by word from stream
    ss >> temp; 
    //Check the given word is integer or not
    if (stringstream(temp) >> found) 
         {
         cout << "Number found: " << found << " " << endl;
         foundRelevantSection = true;
         break; /* exits the while now */
         }
    //no space at the end of string
    temp = ""; 
    }

или вы могли бы тест, найденный в то время как, сначала устанавливая его в 0, и тестируя с && found == 0

Тогда часть, вызывающая findCurrentNumber (int currentNumber, int foundNumber), является мусором (или заполнителем для чего-то более сложного?), как if (findCurrentNumber (searchCurrentNumber, found) == true) просто if (searchCurrentNumber == found), который намного легче читать!

Я не проверял, есть ли еще ошибки в коде, но с разрывом вы определенно получите правильное значение в найденном.

часть 2

Вы уже нашли "точку", поэтому вам не следует искать ее снова!
Я добавил foundRelevantSection в приведенном выше коде, прежде чем перерыв.
Измените следующую часть на (нет, если уместно, нет, если точка найдена):

while (getline (inputFile, line) && foundRelevantSection) 
    {
    //if no matches were found, the function returns "string::npos"
    if(line.find("total") != string::npos) 
        {
        //relevant section ends now
        foundRelevantSection = false;   
        }
    else    
        {
        cout << line << endl;
        }
    }

, надеясь, что это было последний баг ...

...