C++ 将包含多个数字的字符串转换为整数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1321137/
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 19:32:37  来源:igfitidea点击:

Convert String containing several numbers into integers

c++stringinteger

提问by GobiasKoffi

I realize that this question may have been asked several times in the past, but I am going to continue regardless.

我意识到这个问题过去可能被问过几次,但无论如何我都会继续。

I have a program that is going to get a string of numbers from keyboard input. The numbers will always be in the form "66 33 9" Essentially, every number is separated with a space, and the user input will always contain a different amount of numbers.

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

I'm aware that using 'sscanf' would work if the amount of numbers in every user-entered string was constant, but this is not the case for me. Also, because I'm new to C++, I'd prefer dealing with 'string' variables rather than arrays of chars.

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

回答by Jesse Beder

I assume you want to read an entire line, and parse that as input. So, first grab the line:

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

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

Now put that in a stringstream:

现在把它放在一个stringstream

std::stringstream stream(input);

and parse

并解析

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

Remember to include

记得包括

#include <string>
#include <sstream>

回答by GobiasKoffi

The C++ String Toolkit Library (Strtk)has the following solution to your problem:

C ++字符串工具箱库(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;
}

More examples can be found Here

更多例子可以在这里找到

回答by David Rodríguez - dribeas

#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;
   }
 }

回答by David Rodríguez - dribeas

#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;
    }
}

回答by Kirill V. Lyadvinsky

// 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 ) );

回答by MSalters

Generic solution for unsigned values (dealing with prefix '-' takes an extra bool):

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

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.
}

回答by Zed

Here ishow to split your string into strings along the spaces. Then you can process them one-by-one.

以下是如何沿空格将字符串拆分为字符串。然后就可以一一处理了。

回答by Benny

Try strtokento separate the string first, then you will deal with each string.

尝试strtoken先将字符串分开,然后您将处理每个字符串。