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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21594533/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 23:43:34  来源:igfitidea点击:

C++ Extract int from string using stringstream

c++stringstream

提问by Megan

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.

我正在尝试编写一个短行,使用 getline 获取字符串并使用 stringstream 检查它的 int。我在如何检查被检查的字符串部分是否为 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?

稍后我将调整以考虑不包含任何整数的字符串,但现在关于如何通过这部分的任何想法?

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

(目前,我只是输入一个测试字符串,而不是每次都使用 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;
}

回答by jrd1

While your question states that you wish to

虽然您的问题表明您希望

get a string using getline and checks it for an int

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

using stringstream, it's worth noting that you don't need stringstreamat all. You only use stringstreams when you want to do parsing and rudimentary string conversions.

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

A better idea would be to use functions defined by std::stringto find ifthe string contains numbers as follows:

更好的方法是使用由定义的函数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;
}

And thenperform the conversions.

随后进行的转换。

Why use this? Think about happens if you use a stringstream object on something like the following:

为什么要用这个?想想如果你在类似下面的东西上使用 stringstream 对象会发生什么:

"abcdef123ghij"

“abcdef123ghij”

which will simply be parsed and stored as a regular string.

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

回答by sajas

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

您可以将 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;
}

回答by Sergii Khaperskov

Exceptions should not scary you.

异常不应该吓到你。

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;