首页 > 解决方案 > 仅打印那些包含 2 位数字的字符串

问题描述

仅打印那些包含 2 位数字的字符串

“myFile.txt 中的文本是

{粉色双跳34

上升的青蛙 2

执行代码 11

不错 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";
            
        }
        
        

        }


        
    }

我究竟做错了什么?如何检查字符串中是否有 2 位数字?

标签: c++

解决方案


你可以使用stoi如下:

#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;
}

有输出

34 11

test.txt包含

{粉色双跳34

上升的青蛙 2

执行代码 11

不错 4}"

PS:当您在寻找字符串时,只需读取字符串而不是行,然后从该行读取字符串。读取字符串只是让它变得更简单,因为它归结为只是缩小到 2 位数的字符串,然后只是验证它们是否是数字。此外,如评论中所述,请避免使用!file.eof()代码。


推荐阅读