sscanf equivalent for std::string
sscanf equivalent for std::string
我有一个格式为std::string str =" 1001 0104 2325 9999"的字符串,我需要以整数形式存储这四个由空格分隔的子字符串。是否有一种优雅的方式来完成这个任务,就像C中的字符串一样(使用sscanf) ?这不是作业问题。
最干净的方法可能是将stringstream与istream_iterator一起使用,如下所示:
std::string str = "1001 0104 2325 9999";
std::istringstream in(str);
std::vector<int> numbers {
std::istream_iterator<int>(in),
std::istream_iterator<int>()
};
// just to show what we did:
for (int i : numbers)
std::cout << i << "n";
请注意,在您提供的输入中有一点模糊:不清楚您是打算将0104
设置为十进制还是八进制(因为前导零会导致在源代码中解释它)。我上面写的代码将其解释为十进制。如果您希望前导0
表示八进制(并且前导0x
表示十六进制),您可以通过将转换的基数设置为0来做到这一点(至少在内存可用的情况下)。
相关文章:
- cppcheck在const std::string[]上引发警告
- 将std::string传递给WriteConsole API
- 为std::string的某个索引赋值
- std中有类似find_last_of的函数,而string中没有
- 使用 std::string () const 函数启动线程或未来
- 当我们进行一些操作时,应该使用什么'std::string'或'std::stringstream'?
- 如何更改大小(std::string)
- std::string 的对象真的可以移动吗?
- SegFault 同时使用 std::string::operator+= 和函数作为参数
- 无法从 std::string 中提取C++ Unicode 符号
- std::string 构造函数如何处理固定大小的 char[]?
- 确切地说,如何解释 std::getline(stream, string) 函数在C++中填充的字符串
- C++:考虑C++ std::string 中双引号 (") 的字面含义,而不使用反斜杠 (\)
- 'int main(int, int, std::__cxx11::string, std::__cxx11::string)'只需要零或两个参数 [-Wmain]
- C++ 在列表和列表之间选择返回类型<<string>std::p air<string,string>>
- std::string, std::wstring and UTF8
- uan inplace replacement of std::string/std::wstring?
- #define Glib::string std:wstring
- 从 std::string & std::wstring 中获取 char 整数值
- BSTR转换为std::string(std::wstring),反之亦然