简体   繁体   中英

ascii code in a char string

how can i get from a datagenerator datapoint*25+65 is for single char like a, but i want to have in str = abcdefg (doesnt matter which letters)? datapoint creates a value between 0.0 and 1.0. the program for single charakters:

char str;
for(int n; n<60; n++)
{
    str=datapoint*25+65;
    str++;
}
str = '/0';

problem i don't know how to get with this setup a char string like abcd and not only a single letter like a in str.

Try this:

char str[60 + 1]; /* Make target LARGE enough. */
char * p = str; /* Get at pointer to the target's 1st element. */
for(int n = 0; /* INITIALISE counter. */ 
    n<60; 
    n++)
{
  *p = datapoint*25+65; /* Store value by DE-referencing the pointer before
                         assigning the value to where it points. */
  p++; /* Increment pointer to point to next element in target. */
}
*p = '\0'; /* Apply `0`-terminator using octal notation, 
              mind the angle of the slash! */

puts(str); /* Print the result to the console, note that it might (partly) be
              unprintable, depending on the value of datapoint. */

Alternative approach without pointer to current element but with using indexing:

char str[60 + 1]; /* Make target LARGE enough. */
for(int n = 0; /* INITIALISE counter. */ 
    n<60; 
    n++)
{
  str[n] = datapoint*25+65; /* Store value to the n-th element. */
}
str[n] = '\0'; /* Apply `0`-terminator using octal notation, 
                  mind the angle of the slash! */
char str; 
/* should be char str[61] if you wish to have 60 chars
 * alternatively you can have char *str
 * then do str=malloc(61*sizeof(*str));
 */

for(int n; n<60; n++)
/* n not initialized -> should be initialized to 0,
 * I guess you wish to have 60 chars
 */
{
    *(str+n)=datapoint*25+65; 
/* alternative you can have str[n]=datapoint*25+65;
 * remember datapoint is float
 * the max value of data*25+65 is 90 which is the ASCII correspondent for 
 * letter 'Z' ie when datapoint is 1.0

 * It is upto you how you randomize datapoint.
 */
}
str[60] = '\0'; // Null terminating the string.
/* if you have used malloc
 * you may do free(str) at the end of main()
 */

You have to understand that since you are using chars, you can only store a single character at a time. If you want to store multiple characters, use the string class, or a c-string (an array of characters). Also, make sure you initialize the values of str and n. For example:

str = 'a';
n = 0;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM