I am trying to write a function which converts a number to a string. But when I return from the function, the reviving string - according to debug mode - still is empty, so the program outputs nothing.

What am I doing wrong?

#include <iostream>
#include <string>
using namespace std;

string convertNumberToString(int num);
 
int main()
{
	string num=convertNumberToString(7);

	cout<<num<<endl;

	fflush(stdin);
	cin.get();
}

string convertNumberToString(int num)
{
	string scoreString;

	itoa(num,const_cast<char *> (scoreString.c_str()),10);

	return scoreString;

}

Dani AI

Generated

The problem is that the code attempts to make itoa write into the buffer returned by scoreString.c_str() (via const_cast). That pointer is to a const, null-terminated array owned by the string; writing into it is undefined behavior and will not resize the string for you. That explains why the returned string appears empty. was right to suggest a stream-based approach, and was also correct that itoa is non-standard — prefer a standard conversion.

A few safe, standard options:

#include <string>

std::string convertNumberToString(int num) {
    return std::to_string(num); // simplest (C++11+)
}
#include <sstream>

std::string convertNumberToString(int num) {
    std::ostringstream oss;
    oss << num;            // portable, works on older toolchains
    return oss.str();
}

For high-performance, zero-allocation conversion use std::to_chars (C++17):

#include <charconv>

std::string convertNumberToString(int num) {
    std::string s;
    s.resize(12); // enough for a 32-bit int + sign
    auto res = std::to_chars(&s[0], &s[0] + s.size(), num);
    s.resize(res.ptr - &s[0]);
    return s;
}

Notes and cautions: do not write into c_str() or use const_cast to make it writable — that is undefined. If you must use C APIs, write into a local char[] (or std::string::resize and &s[0] in C++11+) and then assign the result into a std::string. Also remove fflush(stdin) — calling fflush on an input stream is undefined behavior. See the standard references for std::string::c_str() and std::to_chars() for details:

Recommended Answers

All 2 Replies

Don't use itoa, but rather use std::stringstream

This should help: Code Snippet
Also, the function itoa() is not defined in the ANSI-C++ standard, so it may not be supported on all platforms.

Hope this helped

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.