C ++使用stringstream从字符串中提取int [英] C++ Extract int from string using stringstream

查看:211
本文介绍了C ++使用stringstream从字符串中提取int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一条短行,该行使用getline获取一个字符串,并使用stringstream检查它是否为int。我在如何检查要检查的字符串部分是否为int方面遇到麻烦。我已经查看了如何执行此操作,但大多数人似乎都抛出了异常-我需要它继续前进,直到达到整数为止。

I am trying to write a short line that gets a string using getline and checks it for an int using stringstream. I am having trouble with how to check if the part of the string being checked is an int. I've looked up how to do this, but most seem to throw exceptions - I need it to keep going until it hits an int.

稍后,我将调整以说明不包含任何整数的字符串,但是现在对如何跳过此部分有任何想法吗?

Later I will adjust to account for a string that doesn't contain any ints, but for now any ideas on how to get past this part?

(目前,我只是输入一个测试字符串,而不是每次都使用getline。)

(For now, I'm just inputting a test string rather than use getline each time.)

int main() {

    std::stringstream ss;
    std::string input = "a b c 4 e";

    ss.str("");
    ss.clear();

    ss << input;

    int found;
    std::string temp = "";

    while(!ss.eof()) {
            ss >> temp;
            // if temp not an int
                    ss >> temp; // keep iterating
            } else {
                    found = std::stoi(temp); // convert to int
            }
    }

    std::cout << found << std::endl;

    return 0;
}


推荐答案

您可以确定其有效性将stringstream转换为int:

You could make of the validity of stringstream to int conversion:

int main() {

std::stringstream ss;
std::string input = "a b c 4 e";
ss << input;
int found;
std::string temp;

while(std::getline(ss, temp,' ')) {
    if(std::stringstream(temp)>>found)
    {
        std::cout<<found<<std::endl;
    }
}
return 0;
}

这篇关于C ++使用stringstream从字符串中提取int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆