Regular doubt

hola people.

I'm new to c++ and I want to give characters to variable but not wanna use the string command like we do for integers.
1
2
3
4
5
6
7
8
9
10
11
12
13

#include <iostream.h>
#include <conio.h>

void main ()
{
char text[40];
text[40]="i want it like that";

cout<<text[40];

getch()
}


so is there something like int , char , float or any thing in which I can assign some text value like the above code which dsnt work
You'd want this:
text = "I want it like that!";

Instead of this:
text[40] = "I want it like that!";

Why don't you want to use a string?
yes use char text = "Iwant it like that!";

that way you make it like an array
In C++ you can't assign a string to an array by doing the following (or anything like it);

 
text[40]="i want it like that";


Why is this disallowed? Because "text[40]" is actually the 41st element of the array "text[]". And having used "char text[40];" to define the array in the first place, then the last element of the array is "text[39]" (remember the FIRST element is text[0]). It turns out that the command; 'text[40] = "i want it like that";' is really an attempt to stuff a string of 20 (or thereabouts) char into a single char block of memory which actually resides _outside_ the memory allocated for the defined array.

So you can see why it doesn't work!

What C++ does allow you to do is to assign the contents of the array at the same time you define the array. You can do this in two ways;

The first gives you an array of 40 char containing the string "i want it like that";

 
char text[40] = "i want it like that";


The second lets the compiler determine the array size, giving you an array exactly large enough to contain the specified string;

 
char text[] = "i want it like that";


If you want to do more than this -- particularly if you want to change the contents of the array while the program is running -- you will need to use string functions - or something like getline() at the very least.
Last edited on
For a C-style string the equivalent of
1
2
char text[40];
text = "blah blah"; // does not work 

is this
1
2
char text[40];
strcpy(text,"blah blah");

Or even better, use strncpy to ensure you do not overwrite the array
(if you are reading it in, for example).
Last edited on
Just adding one thing to dirk's suggestion;

If you choose to use strcpy() make sure you include the appropriate header;

 
#include <cstring> 


Note that this is the C++ version, for C (or C compatibility) use;

 
#include <string.h> 


Last edited on
Thanks every one specially dirk and muzhogg :D
Topic archived. No new replies allowed.