从字符串中分离整数

7

我有一个包含由空格分隔的数字的字符串。请问如何将该字符串拆分为整数?我尝试使用find和substr函数,但是否存在更好的方法呢?


我不确定您所描述的确切格式 - 只是空格分隔的数字吗?一个示例字符串会有所帮助。 - Georg Fritzsche
谷歌搜索“splitting string c ++”得到:http://oopweb.com/CPP/Documents/CPPHOWTO/Volume/C++Programming-HOWTO-7.html - Akusete
4个回答

9

使用stringstream:

#include <string>
#include <sstream>

int main() {
    std::string s = "100 123 42";
    std::istringstream is( s );
    int n;
    while( is >> n ) {
         // do something with n
    }
}

如果每次只有两个值,例如100 123,是否有更好的方法来处理它? - brett
1
@brett,“better”是什么意思? - anon
1
如果始终有两个数字,您可以使用以下代码提取它们,无需使用循环:int x, y; is >> x >> y; - reko_t

2

这个问题已经在C++中如何分割字符串?讨论过。

此外,您可以使用boost库的split函数,在程序中不需要循环即可实现分割。 例如:

boost::split(epoch_vector, epoch_string, boost::is_any_of(","));


1

使用 boost 的版本。Neil 提供的 stringstream 版本要简单得多!

#include <iostream>
#include <vector>
#include <algorithm>
#include <boost/lexical_cast.hpp>
#include <boost/tokenizer.hpp>

int main()
{
  const std::string str( "20 30 40 50" );
  std::vector<int> numbers;
  boost::tokenizer<> tok(str);
  std::transform( tok.begin(), tok.end(), std::back_inserter(numbers), 
                  &boost::lexical_cast<int,std::string> );
  // print them
  std::copy( numbers.begin(), numbers.end(), std::ostream_iterator<int>(std::cout,"\n") ); 
}

1
你甚至不需要使用boost库,只需构造一个std::istringstream is(str);实例,然后执行std::copy(std::istream_iterator<int>(is), std::istream_iterator<int>(), std::back_inserter(numbers)); - reko_t
@reko_t 不错!istream_iterator 期望以空格分隔的项,还是可以处理其他的分隔符? - Brian O'Kennedy
它期望空格分隔的项目,无法处理其他分隔符。 - reko_t

0

在读取和转换多个字符串时,我遇到了一些问题(我发现我必须清除字符串流)。这里是我用多个int/string转换进行读写i/o文件的测试。

#include <iostream>
#include <fstream> // for the file i/o
#include <string>  // for the string class work
#include <sstream> // for the string stream class work

using namespace std;

int main(int argc, char *argv[])
{
    // Aux variables:
    int aData[3];
    string sData;
    stringstream ss;

    // Creation of the i/o file:
    // ...
    // Check for file open correctly:
    // ...

    // Write initial data on file:
    for (unsigned i=0; i<6; ++i)
    {
        aData[0] = 1*i;
        aData[1] = 2*i;
        aData[2] = 3*i;

        ss.str(""); // Empty the string stream
        ss.clear();
        ss << aData[0] << ' ' << aData[1] << ' ' << aData[2];
        sData = ss.str(); // number-to-string conversion done

        my_file << sData << endl;
    }

    // Simultaneous read and write:
    for (unsigned i=0; i<6; ++i)
    {
        // Read string line from the file:
        my_file.seekg(0, ios::beg);
        getline (my_file, sData); // reads from start of file

        // Convert data:
        ss.str(""); // Empty the string stream
        ss.clear();
        ss << sData;
        for (unsigned j = 0; j<3; ++j)
            if (ss >> aData[j]) // string-to-num conversion done
                ;

        // Write data to file:
        my_file.seekp(0, ios::end);
        my_file << 100+aData[0] << ' '; // appends at the end of stream.
        my_file << 100+aData[1] << ' ';
        my_file << 100+aData[2] << endl;
    } 
    // R/W complete.

    // End work on file:
    my_file.close();

    cout << "Bye, world! \n";

    return 0;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接