2

I've got this piece of code in C++ from someone else that I am now working with but I'm not sure why the "std::string()" is been added.

std::ifstream File;
std::stringstream FileName;
FileName << Name; //Name being a string that has been passed as an input to the function.
                 // Eg."MyFile"
newFileName << ".txt"; //"MyFile.txt"

File.open(std::string(FileName.str()).c_str(), std::ios::in | std::ios::binary);

My question is, since str() returns a string, and c_str() gets a string and transforms it into c string, why do we need to put it inside the "string()"? Could it not be writen like:

File.open((FileName.str()).c_str(), std::ios::in | std::ios::binary);
1
  • std::string() create another temp string object, which is unnecessary. Commented Feb 15, 2014 at 12:50

1 Answer 1

1

Yes, it can be written like this.

Using

std::string(FileName.str())

is absolutely meaningless.

Sign up to request clarification or add additional context in comments.

2 Comments

So what I wrote is fine eventhough I don't have "using namespace std;" included in my file, right? Thanks for your quick answer!!
@Mulan - yes, it's fine, because toy don't need to have access to this name in this case, using just .str() is OK.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.