C++ Programming Language: Giving Characters to Variables

Asked By 30 points N/A Posted on -
qa-featured

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.

SHARE
Answered By 0 points N/A #128061

C++ Programming Language: Giving Characters to Variables

qa-featured

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.

Login/Register to Answer

Related Questions