I have a simple function that simply adds two numbers and returns the output like below
#include <stdio.h>
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
double addNum(double num1=0, double num2=0) {
return num1 + num2;
}
int main(int argc, char** argv) {
printf("%.1f + %.1f = %.1f \n", 5.22, 4.66, addNum(5.22, 4.66));
}
This works just fine. Now say I change my addNum
function return type to string
and change the format identifier in printf
to %s
string addNum(double num1=0, double num2=0) {
return to_string(num1 + num2);
}
int main(int argc, char** argv) {
printf("%.1f + %.1f = %s \n", 5.22, 4.66, addNum(5.22, 4.66));
}
But now I get the below error
test.cpp:266:47: error: cannot pass non-POD object of type 'std::__1::string' (aka 'basic_string<char, char_traits<char>, allocator<char> >') to variadic function;
expected type from format string was 'char *' [-Wnon-pod-varargs]
printf("%.1f + %.1f = %s \n", 5.22, 4.66, addNum(5.22, 4.66));
~~ ^~~~~~~~~~~~~~~~~~
test.cpp:266:47: note: did you mean to call the c_str() method?
printf("%.1f + %.1f = %s \n", 5.22, 4.66, addNum(5.22, 4.66));
^
.c_str()
1 error generated.
I do not understand what's going on here. I am returning a string and gave %s
as an identifier as expected. Then why is it still complaining? How do I fix it?