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

问题描述 投票:0回答:3

我正在尝试编写一个短行,使用 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;
}
c++ stringstream
3个回答
4
投票

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

3
投票

虽然您的问题表明您希望

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

使用

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

更好的想法是使用

std::string
定义的函数来查找 if 字符串包含数字,如下所示:

#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”

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


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;
© www.soinside.com 2019 - 2024. All rights reserved.