Strings.

Can someone please tell me why my string doesn't output?

I have this..
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <string>

using namespace std;

int main(){

    int i=0,n;
    string name;
    string name2;
    getline(cin, name);
    n=sizeof(name);

    do
    {
        name2[i]=name[i];
        i++;
    }
    while(i<n);

    cout << "Name is " << name2 << endl;

    return 0;

}


On output it doesn't say what name2 is, it only says "Name is " and that's all. But if i do..

1
2
3
4
5
6
7
8
cout << "Name is ";

    for(int j=0;j<n;j++)
    {
        cout << name2[j];
    }

    return 0;


then it works just fine. So "name" gets copied to "name2". If i try to cout << name2; (the whole thing) it doesn't work, but if i cout << name2[j]; (one by one in a loop) it works. It also works normally when i try to cout << name; Why is that?
Because you're trying to copy data to parts of memory that were never allocated to 'name2'. Just use the assignment operator ('=') without the square brackets and stop trying to treat std::string like it's the same as a cstring.
The first error is on line 12. That does not produce the number of characters that the "name" contains.
You should use: http://www.cplusplus.com/reference/string/string/size/

The second error is on line 16. Within http://www.cplusplus.com/reference/string/string/operator%5B%5D/
Reads:
If pos is not greater than the string length, the function never throws exceptions (no-throw guarantee).
Otherwise, it causes undefined behavior.

The size of "name2" is 0, so everything you think write is undefined behaviour. The size does not change on line 16. It is pure misfortune that your second method to print appears to function.

You should use
http://www.cplusplus.com/reference/string/string/push_back/
or
http://www.cplusplus.com/reference/string/string/operator+=/
or
http://www.cplusplus.com/reference/string/string/append/


But why do a elementwise copy when you could just:
http://www.cplusplus.com/reference/string/string/operator=/
or
http://www.cplusplus.com/reference/string/string/assign/
Last edited on
Topic archived. No new replies allowed.