C ++使用stringstream从字符串中提取int

时间:2014-02-06 05:12:07

标签: c++ stringstream

我正在尝试编写一个使用getline获取字符串的短行,并使用stringstream检查它是否为int。我在如何检查被检查的字符串部分是否为int时遇到问题。我已经查明了如何做到这一点,但大多数似乎都抛出异常 - 我需要它继续前进,直到它遇到一个int。

稍后我将调整为一个不包含任何整数的字符串,但是现在有关于如何通过这部分的任何想法?

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

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

3 个答案:

答案 0 :(得分:3)

虽然您的问题表明您希望

  

使用getline获取一个字符串并检查它是否为int

使用stringstream,值得注意的是您根本不需要stringstream。当您想要进行解析和基本字符串转换时,您只使用字符串流。

更好的想法是使用std::string定义的函数来查找如果字符串包含数字,如下所示:

#include <iostream>
#include <string>

int main() {
    std::string input = "a b c 4 e 9879";//I added some more extra characters to prove my point.
    std::string numbers = "0123456789";
    std::size_t found = input.find_first_of(numbers.c_str());

    while (found != std::string::npos) {
        std::cout << found << std::endl;
        found = input.find_first_of(numbers.c_str(), found+1);
    }

    return 0;
}

然后执行转换。

为什么要用这个?如果您对以下内容使用stringstream对象,请考虑一下:

  

“abcdef123ghij”

将简单地解析并存储为常规字符串。

答案 1 :(得分:2)

你可以将stringstream的有效性转换为int转换:

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

答案 2 :(得分:0)

例外不应该吓到你。

int foundVal;
found = false;

while(!found || !ss.eof()) {
    try
    {
       foundVal = std::stoi(temp);  //try to convert
       found = true;
    }
    catch(std::exception& e)
    {
        ss >> temp; // keep iterating
    }
}

if(found)
    std::cout << foundVal << std::endl;
else
    std::cout << "No integers found" << std::endl;