Why is this function always returning an empty string?
I'm aware of scope of variables but I thought the function would return a copy of the std::string res?
string getNumberOfLines(string absFilePath)
{
int nLines = 0;
ifstream inFile(absFilePath.c_str());
if (!inFile)
return "no lines";
char c;
while (inFile.get(c))
{
if (c == '\n')
nLines++;
}
string res;
sprintf(&res[0], "%d lines.", nLines);
puts(res.c_str()); // prints "40 lines" or etc.
return res;
}
puts(getNumberOfLines("f.txt").c_str()); // outputs nothing
func(const string absFilePath)will copy the string, butfunc(const string& absFilePath)won't.sprintfcannot be used withstd::stringin this way.&res[0]is out of bounds as the string is empty. A good debug compiler will flag this for you. Usestd::cininstead.func(string absFilePath)also copy the string? I've often seenfunc(const string& absFilePath)- why have it constant why not just pass by reference normally?&is what prevents the copy of the string. The const is to prevent accidentally modifying the string passed to the function from outside. The caller may want to reuse it for something else and, as it is an input parameter, not expect it to be changed by the function.