monkeyMoo
monkeyMoo

Reputation: 173

Convert a char ' ' or newline to a string

My goal is to convert ' ' into " ", and '\n' into "\n"

The code below works for general cases, but not with spaces and '\n'. Because the >> and << operators do not take in ' ' and '\n's.

std::string stringFromChar(char a) {
    std::stringstream ss(std::stringstream::in | std::stringstream::out | std::stringstream::binary);
    std::string s;
    ss << a;
    ss >> s;
    return s;
}

I thought by using std::stringstream::binary, it uses a binary number for both reading and writing. Thus, preserving the character, without losing spaces or newlines.

I found that while a is ' ', s turns out to be "".

I know a way to solve this:

std::string stringFromChar(char a) {
    std::stringstream ss(std::stringstream::in | std::stringstream::out | std::stringstream::binary);
    std::string s;
    ss << a;
    s = ss.str();
    return s;
}

Is it true that it doesn't take away the spaces or newline while reading, but they get deleted while writing? And why doesn't using binary with stringstream work?

Also, I tried using ss >> std::noskipws >> s As in:

std::string stringFromChar(char a) {
    std::stringstream ss(std::stringstream::in | std::stringstream::out | std::stringstream::binary);
    std::string s;
    ss << a;
    ss >> std::noskipws >> s;
    return s;
}

It also didn't work. Why? s is still returned as "".

Upvotes: 1

Views: 712

Answers (3)

Treesa
Treesa

Reputation: 1

use ss.get(a) to get each of the characters from the stream without skipping spaces and new line feeds where a is of type char

Upvotes: 0

Loki Astari
Loki Astari

Reputation: 264441

Don't make it so complex:

std::string stringFromChar(char a)
{
    return std::string(1,a);
}

As a secondary note:
The only thing that std::ios::binary does is turn on binary mode. Binary mode stops the conversion of '\n' to/from the line termination sequence (which is a platform specific sequence of characters defined as the end of line).

Upvotes: 2

paddy
paddy

Reputation: 63471

Aurrgh, this all seems awfully complicated...

Why not try this:

std::string stringFromChar(char a) {
    return std::string( &a, 1 );
}

Or this:

std::string stringFromChar(char a) {
    char tmp[2] = { a, 0 };
    return std::string(tmp);
}

Edit: If you insist on using streams, try this:

std::string stringFromChar(char a) {
    std::stringstream ss;
    ss.put(a);
    return ss.str();
}

Upvotes: 1

Related Questions