hkBattousai
hkBattousai

Reputation: 10931

Initializing "const std::string" from "std::istringstream"

I'm trying to parse a file which is in Key<whitespace>Value format. I'm reading the file lines in an std::istringstream object, and I'm extracting a Key string from it. I want to avoid accidentally changing the value of this Key string by making it const.

My best attempt was initializing a temporary VariableKey object, and then making a constant one out of it.

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.
    // ...
}

How do I directly initialize a constant Key string object?

Upvotes: 2

Views: 340

Answers (2)

molbdnilo
molbdnilo

Reputation: 66371

You can avoid the "scratch" variable by extracting the input into a function:

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);

// ...

(Binding the function's result to a const reference extends its lifetime.)

Upvotes: 2

Tony Delroy
Tony Delroy

Reputation: 106116

It's arguably better to separate file I/O from processing, and instead of creating a const Key inside the same function - call a line-processing function that takes a const std::string& key parameter.

That said, if you want to continue with your current model, you can simply use:

const std::string& Key = VariableKey;

There's no need to copy or move anything anywhere. Only const std::string members functions will be accessible via Key.

Upvotes: 3

Related Questions