2016-04-26 82 views
1

我怎麼能從一個datagenerator datapoint*25+65是單個字符像一個,但我想在str = abcdefg(無所謂重要哪些字母)? datapoint創建一個介於0.0和1.0之間的值。 節目單charakters:ascii代碼在char字符串

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

的問題,我不知道如何使用此設置來獲得一個字符的字符串像像在海峽ABCD,而不是隻有一個字母。

+1

一個'char'類型的變量存儲一個字符只要。在'char str'中,你不能存儲''abcdefg'''甚至''ab'',但只能存儲''a'',(注意不同的引號)。 – alk

+2

也許你想要一個* char *的數組。 –

回答

2

嘗試這種情況:

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

感謝您的幫助忘記了n = 0在這裏,我沒有指針的程序,所以我的整個程序沒有得到複製:D – Andreas

+0

我的意思是複雜的命中錯誤的按鈕 – Andreas

0

你必須明白,因爲你正在使用字符,所以你一次只能存儲一個字符。如果要存儲多個字符,請使用字符串類或c字符串(字符數組)。另外,確保你初始化str和n的值。例如:

str = 'a'; 
n = 0; 
+0

'str ='a'是什麼意思? – alk

+0

C中沒有「字符串類」 –

1
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() 
*/