2016-05-15 7 views
1

私はcharの配列を操作して、その場で変更する必要があるという問題があります。例えば、私はシリアルなどを介して文字列を受け取ります。文字列と同じになるようにchar配列が必要です。Arduinoが未知のサイズのchar *を扱っています

例:

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

は、私が試した:

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

しかし、それはそれはunproperly(余分な文字を残す作品でない場合、文字列は、char型の*と同じサイズである場合にのみ動作しますまたはそのようなもの)。 char配列の長さを変更する方法が見つかりませんでした。 arduinoにchar *についての情報はほとんどありません。

すべてのヘルプは本当に安くなります。

+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); 
} 

また、あなたが最後にヌルターミネータ( '\ 0')を入れていることを確認してください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は、利用可能なC++ヘッダーを実際には持っていないことに注意してください(http://www.nongnu.org/avr-libc/user-manual/modules.html)。 –

関連する問題