Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Home » Tip Bank » C++
Language: C++
Expertise: Beginner
Jul 18, 1997

Storing strings in a char array

Question:
This is actually a simpler form of the real problem I am dealing with. I have a array of char like so:
char name[20];
Then, I try to put a string in it:
name[]="George";
This doesn't work; it gives an error.

I know could do this:

char name[20]="George";
which does work, but I want to change the contents as the program runs. Is this possible? I am a beginner using Borland TC++ v3.00 Thanks for any help!

Answer:
Char arrays are considered to have a const type, hence their value cannot be changed once created. The value of the data that they point to can, however, be changed. In case of char arrays you can use the standard C function strncpy. Here is an example.

#include 
#include 

void foo ()
{
   char charArray [20];
   char another[30];

   cin >> another;
   strncpy (charArray,another,20);
}
This example reads a string from the standard input and copies it to the array
charArray
.
DevX Pro
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date