C-style strings in C++

Jun 12, 2012 at 6:25pm
Hello,
I would like to ask a thing that I can't figure out on my own.

In before; I know that in C++ we have really nice library(string) that we can include to use strings without caring about their size, etc.

But yet i want to work on library from C. Except the fact that C looks a bit different, everything's ok.

Yet when I write code, and I want to ask about string, i have to create string(array of char) long enough to hold text that would be any long.

For example, I want to ask you for your name. I would create char[100], since there aren't many names(if any) that would exceed this number.

Yet if there is, I have a problem; my array wasn't long enough.

Also, if your name consist of only 3-12 letters, or even few more, I wasted a bit of memory.

So, here's my question: Is there any way, that I can create string long enough, not bigger, not less?

Thanks in advance.
Jun 12, 2012 at 6:47pm
Yes, you have to dynamically allocate space for your array. Space allocated in this way must be deleted afterward, so to properly create/delete a c-string, you would do this:
1
2
3
4
5
6
7
8
9
10
11
char* str;  // make a char pointer
int i;
cout << "How big do you want: ";
cin >> i;

// Allocate space
str = new char[i];  // notice that i isn't a constant

// Use the array as needed

delete [] str;  // Delete the string when done 


Of course you don't want to ask someone how long their name is. The trick here is to provide a c-string much longer than necessary (1000 rather than 100), and then remove it from scope:
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
26
27
#include <iostream>
using namespace std;

const char* getName();

int main(void)
{
  const char* name = getName();
  cout << "Hi " << name;

  delete [] name;
  cin.get();
  return 0;
}

// While oldName is very long, a newName is made to be just the right length.
// newName is returned and oldName goes out of scope.
const char* getName()
{
  char oldName[1000];  // very long
  cout << "What is your name: ";
  cin.getline(oldName, 999);

  char * newName = new char[strlen(oldName) + 1];
  strcpy(newName, oldName);
  return newName;
}
Last edited on Jun 12, 2012 at 6:49pm
Jun 12, 2012 at 7:02pm
The "C way" of doing what LowestOne posted is by using malloc() / calloc() and free() instead of new[] and delete[].

Otherwise, remember that std::string has the c_str() member function which returns the C-compatible pointer to an array of characters, '\0'-terminated.
Jun 12, 2012 at 7:45pm
Well, some ideas might be useful. Thank you for responding.
:)
Topic archived. No new replies allowed.