从"std::istringstream"初始化"const std::string"
Initializing "const std::string" from "std::istringstream"
我正在尝试解析一个Key<whitespace>Value
格式的文件。我正在读取std::istringstream
对象中的文件行,并从中提取一个Key
字符串。我想通过将其设为const
来避免意外更改此Key
字符串的值。
我最好的尝试是初始化一个临时的VariableKey
对象,然后从中生成一个常量
std::ifstream FileStream(FileLocation);
std::string FileLine;
while (std::getline(FileStream, FileLine))
{
std::istringstream iss(FileLine);
std::string VariableKey;
iss >> VariableKey;
const std::string Key(std::move(VariableKey));
// ...
// A very long and complex parsing algorithm
// which uses `Key` in a lot of places.
// ...
}
如何直接初始化常量Key
字符串对象?
可以说,最好将文件I/O与处理分离,而不是在同一函数内创建const
Key
,而是调用一个接受const std::string& key
参数的行处理函数。
也就是说,如果你想继续你目前的模式,你可以简单地使用:
const std::string& Key = VariableKey;
没有必要在任何地方复制或移动任何东西。只有const
std::string
成员功能可以通过Key
访问。
您可以通过将输入提取到函数中来避免"scratch"变量:
std::string get_string(std::istream& is)
{
std::string s;
is >> s;
return s;
}
// ...
while (std::getline(FileStream, FileLine))
{
std::istringstream iss(FileLine);
const std::string& Key = get_string(iss);
// ...
(将函数的结果绑定到常量引用可以延长其使用寿命。)
相关文章:
- cppcheck在const std::string[]上引发警告
- 将std::string传递给WriteConsole API
- 为std::string的某个索引赋值
- 使用 std::string () const 函数启动线程或未来
- 当我们进行一些操作时,应该使用什么'std::string'或'std::stringstream'?
- 如何更改大小(std::string)
- std::string 的对象真的可以移动吗?
- SegFault 同时使用 std::string::operator+= 和函数作为参数
- 无法从 std::string 中提取C++ Unicode 符号
- std::string 构造函数如何处理固定大小的 char[]?
- 真的没有来自 std::string_view 的 std::string 的显式构造函数吗?
- 将C++ std::string 转换为 UTF-16-LE 编码的字符串
- 重载 + 自己的类和 std::string 的运算符
- 如何使用 std::string 作为 QHash 的键?
- 将日语 wstring 转换为 std::string
- 可以从std::string继承以提供类型一致性吗
- 构造函数采用std::string_view与std::string并移动
- 在共享缓冲区内存中创建 ::std::string 对象
- std::string.size() 未知行为
- Valgrind 在 std::string::swap 中报告 SIGILL