gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 01:19:03 24 4
gpt4 key购买 nike

我正在尝试编写一个短行,使用 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;
}

最佳答案

你可以判断 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;
}

关于C++使用stringstream从字符串中提取int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21594533/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com