a Simple code

Hi,

I'm new in programming. I try to insert the letter 't' in a string with a for loop. Compiler is fine, no error but when I try to see what is in my variable with cout <<, it's empty.

Any Idea?

Thanks.

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

using namespace std;

int main()
{
    string lol;
    int comp;

    cout << "number of letter : ";
    cin >> comp;

    for(int i=0; i<=comp; i++)
    {
        lol[i] = 't';
    }

    cout << lol;

    return 0;

}
The string is uninitialized, so it has undefined size ( Or zero I'm not sure of the details ).

Instead, init the string to a word, and in your for loops use:

for(int i = 0; i < lol.length() comp; i++)

Hope that works I haven't tested it yet.

EDIT:

Go with MiiNiPaa approach, I never knew string had a push_back and resize function.
Last edited on
The string is uninitialized
It is. Default constructor is called and lol now is an empty string with the size of 0.
So it does not have any letters inside so any attempt to access them with operator[] can lead to disaster.

Either use lol.push_back('t'); in a loop to add letters to the end, or make use of one of the many string constructors:
1
2
3
4
int comp;
std::cout << "number of letter : ";
std::cin >> comp;
std::string lol(comp, 't');
, or use a .resize() member:
1
2
3
4
5
std::string lol;
int comp;
std::cout << "number of letter : ";
std::cin >> comp;
lol.resize(comp, 't');

Thanks you very much :) I thought can uninitialized like a INT.

and thank for suggestion too.
Topic archived. No new replies allowed.