将包含多个数字的String转换为整数

时间:2009-08-24 08:32:39

标签: c++ string integer

我意识到这个问题在过去可能已被多次询问过,但我会继续这样做。

我有一个程序可以从键盘输入中获取一串数字。数字将始终采用“66 33 9”的形式。基本上,每个数字都用空格分隔,用户输入将始终包含不同数量的数字。

我知道如果每个用户输入的字符串中的数字量不变,使用'sscanf'会有效,但对我来说情况并非如此。另外,因为我是C ++的新手,所以我更喜欢处理'字符串'变量而不是字符数组。

8 个答案:

答案 0 :(得分:35)

我假设您想要读取整行,并将其解析为输入。所以,先抓住这条线:

std::string input;
std::getline(std::cin, input);

现在把它放在stringstream

std::stringstream stream(input);

并解析

while(1) {
   int n;
   stream >> n;
   if(!stream)
      break;
   std::cout << "Found integer: " << n << "\n";
}

请记住包含

#include <string>
#include <sstream>

答案 1 :(得分:19)

C++ String Toolkit Library (Strtk)针对您的问题提供了以下解决方案:

#include <iostream>
#include <string>
#include <deque>
#include <algorithm>
#include <iterator>

#include "strtk.hpp"

int main()
{
   std::string s = "1 23 456 7890";

   std::deque<int> int_list;
   strtk::parse(s," ",int_list);

   std::copy(int_list.begin(),
             int_list.end(),
             std::ostream_iterator<int>(std::cout,"\t"));

   return 0;
}

可以找到更多示例Here

答案 2 :(得分:9)

#include <string>
#include <vector>
#include <iterator>
#include <sstream>
#include <iostream>

int main() {
   std::string input;
   while ( std::getline( std::cin, input ) )
   {
      std::vector<int> inputs;
      std::istringstream in( input );
      std::copy( std::istream_iterator<int>( in ), std::istream_iterator<int>(),
         std::back_inserter( inputs ) );

      // Log process: 
      std::cout << "Read " << inputs.size() << " integers from string '" 
         << input << "'" << std::endl;
      std::cout << "\tvalues: ";
      std::copy( inputs.begin(), inputs.end(), 
         std::ostream_iterator<int>( std::cout, " " ) );
      std::cout << std::endl;
   }
 }

答案 3 :(得分:3)

#include <string>
#include <vector>
#include <sstream>
#include <iostream>
using namespace std;

int ReadNumbers( const string & s, vector <int> & v ) {
    istringstream is( s );
    int n;
    while( is >> n ) {
        v.push_back( n );
    }
    return v.size();
}

int main() {
    string s;
    vector <int> v;
    getline( cin, s );
    ReadNumbers( s, v );
    for ( int i = 0; i < v.size(); i++ ) {
        cout << "number is " <<  v[i] << endl;
    }
}

答案 4 :(得分:1)

Here is如何将字符串拆分为沿空格的字符串。然后你可以逐个处理它们。

答案 5 :(得分:1)

// get string
std::string input_str;
std::getline( std::cin, input_str );

// convert to a stream
std::stringstream in( input_str );

// convert to vector of ints
std::vector<int> ints;
copy( std::istream_iterator<int, char>(in), std::istream_iterator<int, char>(), back_inserter( ints ) );

答案 6 :(得分:1)

无符号值的通用解决方案(处理前缀' - '需要额外的布尔值):

template<typename InIter, typename OutIter>
void ConvertNumbers(InIter begin, InIter end, OutIter out)
{
    typename OutIter::value_type accum = 0;
    for(; begin != end; ++begin)
    {
        typename InIter::value_type c = *begin;
        if (c==' ') {
            *out++ = accum; accum = 0; break;
        } else if (c>='0' && c <='9') {
            accum *= 10; accum += c-'0';
        }
    }
    *out++ = accum;
       // Dealing with the last number is slightly complicated because it
       // could be considered wrong for "1 2 " (produces 1 2 0) but that's similar
       // to "1  2" which produces 1 0 2. For either case, determine if that worries
       // you. If so: Add an extra bool for state, which is set by the first digit,
       // reset by space, and tested before doing *out++=accum.
}

答案 7 :(得分:0)

首先尝试strtoken分隔字符串,然后处理每个字符串。