Vihaan Verma
Vihaan Verma

Reputation: 13143

QString to const std::string

I want to assign the value in QString to a const std::string

QString qfile("some value");

this is the const std::string variable

const std::string file

The code that I m using

file = qfile.toStdString();

above codes works fine for a normal std::string . But there is some problem because of the keyword 'const'. How do I solve it ?

Upvotes: 0

Views: 4005

Answers (3)

weggo
weggo

Reputation: 134

You can also get rid of the const by making copy of the return value of toStdString():

QString str("text");
std::string std_str(str.toStdString());

Upvotes: 0

Frerich Raabe
Frerich Raabe

Reputation: 94319

Don't use the assignment operator to initialize the std::string object but rather initialize the variable directly.

const std::string file = qfile.toStdString();

That aside, please make sure that you're aware of what encoding QString::toStdString() uses; unlike QString, std::string is encoding-agnostic (it's a string of bytes, not characters).

Upvotes: 7

Jake1164
Jake1164

Reputation: 12359

Constants are expressions with a fixed value.

http://www.cplusplus.com/doc/tutorial/constants/

Upvotes: 1

Related Questions