I’m new to C++ and I get this error:
expression must have integral or unscoped enum type
when I’m using char*, because I couldn’t get normal strings to work.
Here’s my code:
#include <iostream>
#include <string>
#include <fstream>
#include "text.h"
#include <string.h>
void out(char* output)
{
std::ofstream logfile ("server.log", std::ios::app);
if (logfile.is_open())
{
logfile << output << "\n";
logfile.close();
}
else
{
std::cout << FAIL_OPEN_LOG_MSG_ENG;
}
std::cout << output;
}
void log(char* output)
{
out("[INFO]" << output << "\n");
}
void error(char* output)
{
std::cout << "[ERROR]" << output << "\n";
}
void warn(char* output)
{
std::ofstream logfile;
std::cout << "[WARN]" << output << "\n";
}
int main()
{
log(LOAD_MSG_ENG);
log(START_TESTS_MSG_ENG);
return 0;
}
What I tried
I tried replacing with char and it didn’t like normal strings, for some reasons.
>Solution :
"[INFO]" << output << "\n" is not a valid way to join char* strings together. That operator only works when using classes that implement it, such as std::ostream.
For example, in this code:
std::cout << "[ERROR]" << output << "\n";
std::cout is a (reference to a) std::ostream object. So, the compiler calls std::cout << "[ERROR]" first, which returns an std::ostream& reference to the std::cout object. Then, the compiler calls << output on that object, then calls << "\n" on the object, etc. So, you are not actually joining the strings together, you are printing them individually, and the stream is internally joining the prints together.
Since there is no std::ostream object being used in code like this:
out("[INFO]" << output << "\n");
You end up with the compiler error, since you can’t use operator<< in this context.
To do what you are attempting, you would have to use C-style string concatenations instead, eg:
#include <cstring>
void log(char* output)
{
char *buffer = new char[6 + std:::strlen(output) + 2];
std::strcpy(buffer, "[INFO]");
std::strcat(buffer, output);
std::strcat(buffer, "\n");
/* Alternatively:
std::sprintf(buffer, "[INFO]%s\n", output);
*/
out(buffer);
delete[] buffer;
}
Otherwise, you can use a local std::ostringstream object in order to use operator<<, eg:
#include <sstream>
void log(char* output)
{
std::ostringstream oss;
oss << "[INFO]" << output << "\n";
// if you change out() to take a 'const char*' instead,
// you can then drop this const_cast...
out(const_cast<char*>(oss.str().c_str()));
}
But really, you should be using std::string instead of char* in the first place, then you can use its operator+ to join strings together, eg:
#include <string>
void out(const std::string& output)
{
...
}
void log(const std::string& output)
{
out("[INFO]" + output + "\n"); // <-- HERE
}
...