2016-05-15 25 views
1

我有一個問題,在這個問題中,我必須使用一個char數組並對其進行修改。例如,我通過Serial或其他方法接收一個字符串,並且我需要該char數組與String相同。Arduino與未知大小的字符*工作

例子:

char* pepe = "whatever"; 
String stringReceived = "AnyStringOfUnknownSize"; 

我想:

For(int i=0; i< stringReceived.lenght(); i++){ 
pepe[i] = stringReceived.charAt(0); 
} 

但如果字符串大小爲字符*同樣,如果不是它的工作原理unproperly(留下多餘的字符它只能或類似的東西)。我沒有找到任何修改char數組長度的方法。在arduino中沒有關於char *的很多信息。

任何幫助將真正貶低。

+0

請務必在年底把一個空終止符( '\ 0')。 –

+0

您一直非常樂於助人,非常感謝,請將此評論寫爲答案,以便我可以將其選爲答案解答。乾杯 –

回答

1

確保您在結尾處放置了空終止符('\ 0')。

#include <string> 
#include <iostream> 

int main(){ 

    //your initial data 
    char pepe[100]; 
    std::string stringReceived = "AnyStringOfUnknownSize"; 

    //iterate over each character and add it to the char array 
    for (int i = 0; i < stringReceived.length(); ++i){ 
    pepe[i] = stringReceived.at(i); 
    std::cout << i << std::endl; 
    } 

    //add the null terminator at the end 
    pepe[stringReceived.length()] = '\0'; 

    //print the copied string 
    printf("%s\n",pepe); 
} 

或者,你應該考慮使用strcpy

#include <string> 
#include <iostream> 
#include <cstring> 

int main(){ 

    //your initial data 
    char pepe[100]; 
    std::string stringReceived = "AnyStringOfUnknownSize"; 

    //copy the string to the char array 
    std::strcpy(pepe,stringReceived.c_str()); 

    //print the copied string 
    printf("%s\n",pepe); 
} 
+0

請注意,AVR Arduinos [實際上並沒有](http://www.nongnu.org/avr-libc/user-manual/modules.html)可用的C++頭文件。 –