Doubt about strings

Hey everyone I have the following question:

When I want to create a string s of size k if I do it like:
string s(k); I will get a compilation error.

However if I initialize the positions of the string with, for example, dots
string s(k, '.'); I get no error when compiling.

Why does this happen?

Is there a way of creating a string of fixed size without the need of initialising all the positions? Because it makes the program slower...

Thanks!

You are creating strings the wrong way. Strings doesn't need to be initialized with a size. These are not C strings. You could just do:

1
2
3
4
string s = "Bla bla bla I am boss muahhahahahaha";
string z;
cin >> z;
cout << "You entered: " << z << endl;


Doesn't matter. Strings don't have a fixed size.
Last edited on
But I want to have a string with a precise size.

If I don't initialize it with that certain size, when trying to access a position I will get an invalid memory reference error.
Last edited on
Why does this happen?

If you look at the std::string constructors, you will see that there's no constructor that just takes the size. The closest is what you're already using, the "fill constructor".
http://www.cplusplus.com/reference/string/string/string/

If you don't want to fill the string with data, you could create then resize it.

1
2
3
std::string s;

s.resize(k);


Just an idea, perhaps you should look into std::vector if your strings are used to hold non-text data.
If you want strings with a precise size, you are then looking for C-Style strings.

Here is how to use them:
 
char s[25]; //Declare a string (a char array actually) of size 25. 


Just an example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
//C-Style string example
#include <iostream>

using namespace std;

int main()
{
    char name[15]; //Declare a char array (C-String) of size 15
    
    cout << "Please enter your name: ";
    cin >> name; //Use it like a normal string.
    cout << "Hello " << name << "!" << endl; //Can print it too.
    return 0;
}
Topic archived. No new replies allowed.