一个字符串作为输入,由数字组成,我想在 C++ 中将其转换为整数数组。
#include <string>
#include <iostream>
#include <sstream>
using std::string;
using std::stringstream;
using std::cout;
using std::endl;
int main(int argc,char** argv) {
string num="-24 2 90 24 50 76";
stringstream stream(num);
while(stream){
int n;
stream>>n;
cout<<n<<endl;
}
return 0;
}
输出(GCC):
-24 2 90 24 50 76 76
为什么我会获得额外的值(value),将它们转换为整数数组的效率是什么?
更新:
如果字符串流包含除空格以外的分隔符,如何解析?
例如:
string num="-24,2,90,24,50,76";
最佳答案
文件结束条件是不在成功解析时设置的,你必须在解析后检查流的状态。
第二个76
基本上纯属偶然。不成功的解析使目标操作数保持不变,并且因为您没有初始化 n
,所以它可以是任何东西。
快速修复:
stream>>n;
if (stream)
cout<<n<<endl;
更干净的修复:
int n;
while(stream >> n){
cout<<n<<endl;
}
要存储这些整数,规范的方法是在元素数量未知的情况下使用 std::vector
。示例用法:
std::vector<int> values;
int n;
while(stream >> n){
...do something with n...
values.push_back(n);
}
但是,您可以在流上使用迭代器并使用以下内容:
// Use std::vector's range constructor
std::vector<int> values(
(std::istream_iterator<int>(stream)), // begin
(std::istream_iterator<int>())); // end
关于c++ - 将包含数字的字符串解析为整数数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17724925/