【问题标题】:ascii code in a char stringchar 字符串中的 ascii 代码
【发布时间】:2016-04-26 18:03:30
【问题描述】:

我如何从数据生成器中获取datapoint*25+65 是针对像 a 这样的单个字符,但我想在 str = abcdefg 中拥有(不管哪个字母)? datapoint 创建一个介于 0.0 和 1.0 之间的值。 单字程序:

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

问题我不知道如何通过这种设置获得一个像 abcd 这样的字符字符串,而不仅仅是像一个 in str 那样的单个字母。

【问题讨论】:

  • char 类型变量仅存储一个字符。在char str 中,您不能存储"abcdefg",甚至不能存储"ab",而只能存储'a',(注意不同的引号)。
  • 也许你想要一个char数组

标签: c string char int


【解决方案1】:

试试这个:

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. */

没有指向当前元素的指针但使用索引的替代方法:

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! */

【讨论】:

  • 感谢您的帮助忘记了 n=0 在这里我采用了没有指针的程序,所以我的整个程序不会复杂化:D
【解决方案2】:
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()
 */

【讨论】:

    【解决方案3】:

    您必须了解,由于您使用的是字符,因此一次只能存储一个字符。如果要存储多个字符,请使用字符串类或 c-string(字符数组)。此外,请确保初始化 str 和 n 的值。例如:

    str = 'a';
    n = 0;
    

    【讨论】:

    • str = 'a'; 是干什么用的?
    • C 中没有“字符串类”。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-29
    • 1970-01-01
    • 1970-01-01
    • 2016-09-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多