I got code that follows:
char* writeSpace(int i)
{
fputs(" " + (30-i), stdout);
}
printf("#%i key: %s%svalue: %s%s value2: %s", id, key, writeSpace(10), value, writeSpace(8), value2);
my output should look something like:
#1 key: foo value: bar value2: foobar
but it isn’t. it looks like:
#1 key: foo(null)value: bar(null)value2: foobar(null)
What’s wrong with my code?
Well, you’re
fputting all those spaces to the console, so you get them first.Then you’re outputting everything else, so you get that next.
Perhaps you meant for
writeSpaceto return a C-style string, rather than print it to the console.But be sure that you allocate space for it! Since ownership of memory buffers gets a bit hinky, it’s best to allocate space outside of the function.
And consider using actual C++ features like iostreams and
std::string. It’ll be much easier:I recommend these resources for learning idiomatic C++.