我正在尝试解析 Key<whitespace>Value
中的文件格式。我正在读取 std::istringstream
中的文件行对象,我正在提取 Key
来自它的字符串。我想避免意外更改此 Key
的值字符串通过使其 const
.
我最好的尝试是初始化一个临时的 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
访问。
关于c++ - 从 "const std::string"初始化 "std::istringstream",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33516600/