将特定数量的字符从 std::basic_istream 复制到 std::string
Copy specific number of characters from std::basic_istream to std::string
从
std::basic_istream
中提取特定数量的字符并将其存储在std::string
中是一种好的、安全的方法是什么?
在下面的程序中,我使用char[]
最终获得result
,但我想避免使用 POD 类型并确保更安全、更易于维护:
#include <sstream>
#include <string>
#include <iostream>
#include <exception>
int main()
{
std::stringstream inss{std::string{R"(some/path/to/a/file/is/stored/in/50/chars Other data starts here.)"}};
char arr[50]{};
if (!inss.read(arr,50))
throw std::runtime_error("Could not read enough characters.n");
//std::string result{arr}; // Will probably copy past the end of arr
std::string result{arr,arr+50};
std::cout << "Path is: " << result << 'n';
std::cout << "stringstream still has: " << inss.str() << 'n';
return 0;
}
选择:
- 将整个流转换为前面的字符串:
std::string{inss.c_str()}
- 这似乎很浪费,因为它会复制整个流。
- 编写模板函数以接受
char[]
- 这仍将使用中间 POD 数组。
- 在循环中使用
std::basic_istream::get
来读取所需的字符数以及std::basic_string::push_back
- 循环似乎有点笨拙,但它确实避免了数组。
只需将其直接读取到result
字符串中即可。
#include <sstream>
#include <string>
#include <iostream>
#include <exception>
int main()
{
std::stringstream inss{std::string{R"(some/path/to/a/file/is/stored/in/50/chars Other data starts here.)"}};
std::string result(50, ' ');
if (!inss.read(&result[0], result.size()))
throw std::runtime_error("Could not read enough characters.n");
std::cout << "Path is: " << result << 'n';
std::cout << "stringstream still has: " << inss.str() << 'n';
return 0;
}
自 C++11 起,以下保证有关std::string
的内存布局(来自 cpp首选项)。
basic_string
的元素是连续存储的,也就是说,对于basic_string s
,&*(s.begin() + n) == &*s.begin() + n
[0, s.size())
中的任何n
,或者,等价地,指向s[0]
的指针可以传递给期望指向CharT[]
数组的第一个元素的指针的函数。 (自C++11起)
相关文章:
- 使用std::multimap迭代器创建std::list
- C++中std::resize(n)和std::shrink_to_fit之间的区别
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 如何导出包含具有"std::unique_ptr"值的"std::map"属性的
- 从持续时间构造std::chrono::system_clock::time_point
- std::具有相同基类的类的变体
- std::向量与传递值的动态数组
- 使用std::vector的OpenCL矩阵乘法
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- std::condition_variable::wait()如何评估给定的谓词
- 如何获取std::result_of函数的返回类型
- std::原子加载和存储都需要吗
- 将对象移动到std::shared_ptr
- POCO::PostgreSQL:如何将std::vector支持添加到`Binder::bind`
- 使用一个考虑到std::map中键值的滚动或换行的键
- 如何从 std::atomic 中提取指针 T<T>?
- 为什么 std::unique 不调用 std::sort?
- 使用std::函数映射对象方法
- 字符串C :libc abi.dylib:终止未被发现的类型std :: out_of_range:basic