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

Gob*_*ffi 31 c++ string integer

我意识到这个问题可能在过去曾多次被问过,但我会继续不管.

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

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

Jes*_*der 36

我假设您想要读取整行,并将其解析为输入.所以,首先抢线:

std::string input;
std::getline(std::cin, input);
Run Code Online (Sandbox Code Playgroud)

现在把它放在stringstream:

std::stringstream stream(input);
Run Code Online (Sandbox Code Playgroud)

和解析

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

记得包括

#include <string>
#include <sstream>
Run Code Online (Sandbox Code Playgroud)

  • 你的意思是解析:`int n; while(stream >> n){std :: cout <<"找到整数:"<< n <<"\n";}`?更清洁 (23认同)
  • 甚至解析:`for (int n; stream &gt;&gt; n;) {std::cout &lt;&lt; "Found integer: " &lt;&lt; n &lt;&lt; "\n";}` (3认同)

小智 19

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;
}
Run Code Online (Sandbox Code Playgroud)

更多例子可以在这里找到


Dav*_*eas 10

#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;
   }
 }
Run Code Online (Sandbox Code Playgroud)

  • 只要保留`std ::`前缀,就可以+1.它们的可读性是主观的(我,习惯了它们,发现阅读效果要好得多),但通过完全限定名称提高清晰度是客观的. (8认同)
  • @j_random_hacker:我实际上并不害怕命名空间污染.但是,如果每个名称都具有完全限定条件,则可以更轻松地查看其来源.("哦,这是一个专有的'矢量'模板!")很多年前,在我参与的一个项目中,我们决定完全限定所有名称.那时候看起来很滑稽,但在两周内变得正常.我一直站在争论的两边,永远不会回去.可读性是一个可以通过使用改变的主观问题.清晰是客观的. (4认同)
  • 使用单个"using namespace std"替换1000"std ::"s时+1 并提到你需要的标题. (3认同)