Elements of a String

I'm trying to declare specific elements of a string and failing horribly.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <string>

using namespace std;

int main ()
{
    string s1;
    string s2;
   
    s1 = "some words";
    s2[0] = s1[2];
    s2[1] = s1[3];

    cout << s2;
}


That's basically what I want to do and it compiles just fine but if you try to run it it freaks out. "Debug Assertion Failed!". So why doesn't this work and how can I work around it? Thanks.
The problem lies in the fact that you haven't allocated any memory to s2. Try adding:

s2 = "ww";
Last edited on
GodPyro is right.

You need to be aware of a subtlety in std::string - read here:

http://www.cplusplus.com/reference/string/string/operator[]/

This means, if you do this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <string>

using namespace std;

int main ()
{
    string s1;
    string s2;
   
    s1 = "some words";
    s2.at(0) = s1[2];
    s2.at(1) = s1[3];

    cout << s2;
}


you will crap out during runtime, as expected.

terminate called after throwing an instance of 'std::out_of_range'
  what():  basic_string::at
Abort trap


So you can use [] when you can ensure that you are indexed within s2.size()-1.
Otherwise, use at().
Yeah I thought that might be it but still no luck...
Still no luck with what? That is definitely the problem.
Sorry, you're right. I got it working using [] as long as the string was initialized at the value in the brackets, but I'm having trouble understanding how to use .at() for values that haven't been initialized

1
2
3
4
5
6
7
8
9
10
11
12
13
14
string s1;
string s2;

s2 = "ww";
s1= "some words";

size_t i = 2;

s2[0] = s1[2];
s2[1] = s1[3];

s2.at(i) = s1[4];

cout << s2;


That doesn't work and I can't tell what I should be doing differently from the reference page for string::at.
at(i) will insert data at the position, i, in the string but you still have to allocate memory to it. The at() command won't do that for you automatically.
The reason your code doesn't work is because Line 4 only initializes s2[0] and s2[1].
s2[2] is '\0' and "out-of-bounds" for .at().

I'm having trouble understanding how to use .at() for values that haven't been initialized


You shouldn't use .at() or [] for values that haven't been initialized!!!

Initialize the string first. At least do something like this:

string s2(10,' '); // fill s2 with 10 blanks - initialize out as many as you plan to read
Last edited on
haha ok I understand now. Thanks for your help guys.
You're welcome :)
Topic archived. No new replies allowed.