-1

printing only those strings that include 2-digit number

the text inside "myFile.txt is

{the pink double jump 34

the rising frog 2

doing the code 11

nice 4 } "

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

int main()
{
    
    std::string path = "myFile.txt";

    std::ifstream de;

    de.open(path);


    if (!de.is_open()) {
        std::cout << "nah";
    }
    else {
        std::cout << "file is opened";


        std::string str;


        while (!de.eof()) {
            std::getline(de, str);

            for (int i = 0; i < str.length(); i++) {
                int aa = 10;
                if (str[i] > aa) {
                    str = "0";
                }
            }
    
            std::cout << str << "\n\n";
            
        }
        
        

        }


        
    }

what am I doing wrong? how can I check if there is any 2-digit number inside the string?

  • [`std::regex`](https://en.cppreference.com/w/cpp/regex) will be useful. – MikeCAT Mar 21 '21 at 17:14
  • 1
    Also note that your usage of ` while (!de.eof())` is [wrong](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons). – MikeCAT Mar 21 '21 at 17:15

1 Answers1

1

You could use stoi as follows:

#include <fstream>
#include <iostream>
#include <string>
#include <vector>

int main()
{
    std::ifstream inp("test.txt");
    std::string word;
    std::vector<std::string> listOfTwoDigitStrings;
    while(inp>>std::ws>>word) {
        if(word.length() == 2) {
            int num = std::stoi(word);
            if(num >= 10 && num <= 99) {
                listOfTwoDigitStrings.push_back(word);
            }
        }
    }
    for(const auto& word: listOfTwoDigitStrings) {
        std::cout<<word<<' ';
    }
    std::cout<<'\n';
    return 0;
}

which has the output

34 11

when test.txt contains

{the pink double jump 34

the rising frog 2

doing the code 11

nice 4 } "

P.S.: As you're looking for strings, just read in strings rather than lines and then reading off strings from that line. Reading off strings just makes it simpler since it boils down to just narrowing down to 2-digit strings and then just verifying whether they are numbers or not. Also, as mentioned in the comments, refrain from !file.eof() code.

Zoso
  • 3,273
  • 1
  • 16
  • 27