Marcus
Marcus

Reputation: 5

How do I take a characters and turn it into a string? C++

I'm just trying to use the alphabet to try and make words/names. When I do this the cout end up outputting nothing.

#include <iostream>
#include <ctime>
#include <string>
#include <stdlib.h>

using namespace std;
int main() {
    char Alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    char alphabet[] = "abcdefghijklmnopqrstuvwxyz";
    string n;

    n[0] = Alphabet[10];
    n[1] = alphabet[4];
    n[2] = alphabet[21];
    n[3] = alphabet[8];
    n[4] = alphabet[13];
    cout << n << endl;
}

Upvotes: 0

Views: 78

Answers (3)

Stephan Lechner
Stephan Lechner

Reputation: 35154

When you define n as string n;, then n will be an empty string (zero size and unspecified capacity), and accessing a string with an index beyond its size is undefined behaviour.

There are two principal ways to overcome this:

(1) Use operator += like in n += Alphabet[10];, such that the string object will adapt its size accordingly. Note that this may lead to realloc-operations internally from time to time.

(2) if you know the size in advance, with string n(5, ' ') you may reserve enough space in advance (and fill the string up with blanks in this case), such that realloc-operations will not have to occur.

Upvotes: 0

rain city
rain city

Reputation: 217

When you create a string with string n;, an empty string is created. It has length zero, therefore trying to access character positions within the string with n[0] etc. does not work. These simply do not exist at that point.

As said in another answer, you can use the member function push_back to add a character to a string, increasing its length by one.

Upvotes: 0

scohe001
scohe001

Reputation: 15446

Your issue here is that n is an empty string, meaning you're trying to access indexes that don't exist.

To add characters to the string, you could use the string member function, push_back

n.push_back(Alphabet[10]);
n.push_back(alphabet[4]);
...

Alternatively, the += operator would also work:

n += Alphabet[10];
n += alphabet[4];
...

Furthermore, I'd suggest using .at() over the subscript operator ([]) with your strings, as .at() will do bounds checking for you (which would have made this issue a little more obvious).

Upvotes: 5

Related Questions