Asked By
rachel daws
30 points
N/A
Posted on - 06/24/2011
Hi,
I'm new to c++ and I want to give characters to variable, but not want use the string command like we do for integers.
#include <iostream.h>
#include <conio.h>
void main ()
{
char text[40];
text[40]="i want it like that";
count<<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 doesn't work. Thank you.
Answered By
ibrahim
0 points
N/A
#128061
C++ Programming Language: Giving Characters to Variables
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.