Problem with variable char values
Feb 18, 2014 at 7:20pm UTC
i wanted to be able to change the value of a char based on user input. I am not sure how to achieve this. Below is the section of code I am trying to achieve this in.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
char title_name[50];
if (front_or_back == 0){
choose = 0;
title_name[0] = "f" ;
title_name[1] = "r" ;
title_name[2] = "o" ;
title_name[3] = "n" ;
title_name[4] = "t" ;
}
else {
choose = 50;
title_name[0] = "b" ;
title_name[1] = "a" ;
title_name[2] = "c" ;
title_name[3] = "k" ;
}
I have also tried
1 2 3 4 5 6 7 8 9 10 11
char title_name[50];
if (front_or_back == 0){
choose = 0;
title_name[] = "front" ;
}
else {
choose = 50;
title_name[] = "back" ;
}
The value front_or_back is decided real time by the user. Any advice would be great, thanks.
Feb 18, 2014 at 7:25pm UTC
The easiest way to do this is to use a string instead of a char array:
1 2 3 4 5 6 7 8 9 10 11
string title_name;
if (front_or_back == 0)
{
choose = 0;
title_name = "front" ;
}
else
{
choose = 50;
title_name = "back" ;
}
Or if you must use char arrays... note that a char array must be end with a null terminator (ie, character 0). This signifies the end of the string data.
So your first approach was close:
1 2 3 4 5 6 7 8 9 10 11
char title_name[50];
if (front_or_back == 0){
choose = 0;
title_name[0] = 'f' ; // <- 'single' quotes instead of "double" quotes
title_name[1] = 'r' ;
title_name[2] = 'o' ;
title_name[3] = 'n' ;
title_name[4] = 't' ;
title_name[5] = 0; // <- null terminator
}
Of course... that's very clunky and unwieldly. A better way is to use the strcpy function to set the string data:
1 2 3 4 5 6
char title_name[50];
if (front_or_back == 0){
choose = 0;
strcpy(title_name,"front" );
}
Last edited on Feb 18, 2014 at 7:26pm UTC
Feb 18, 2014 at 7:44pm UTC
Thank you very much.
Topic archived. No new replies allowed.