정수와 더블을 문자 배열에 넣습니다.

Serial.print ()를 사용하여 테이블에 텍스트와 숫자를 혼합하여 인쇄하고 싶습니다. char 배열에서. 내 문제는 서로 다른 데이터 유형 간의 변환입니다. 내 생각은 변수 i가있는 for 루프의 행 데이터와 j 변수가있는 for 루프의 열을 인쇄하는 것입니다.

다음 예제에서는 두 개의 변수가 있고 하나는 정수 유형입니다. 두 번째는 더블입니다. 이제 문자 배열에 변수 값을 추가하고 싶지만 “이 작업을 수행하는 방법을 찾을 수 없습니다 …

주 프로그램에서 변수는이 데이터 유형을 가져야하며 나중에 char 배열에 삽입해야합니다.

누군가이 문제에 대한 해결책이 있습니까?

다음은 작은 예제 코드입니다.

int a = random(0, 100); double b = random(0, 100); char* myStrings[][6] = {"This is string 1", "This is string 2", "This is string 3", "This is string 4", "This is string 5", "This is string 6" }; void setup() { Serial.begin(9600); } void loop() { //now put the integer and double variables into the char array in the second column //Print the values for (int i = 0; i < 2; i++) { for (int j = 0; j < 6; j++) { Serial.print(myStrings[i][j]); Serial.print(" "); delay(100); } Serial.println(); } } 

미리 감사드립니다.

Guss

편집 : 출력은 다음과 같이 표시되어야합니다. 헤드 라인 (이 예에서는 “This is string 1 “,”This is string 2 “…) 다음 행의 변수 값입니다. 다음과 같아야합니다.

This is String 1 This is String 2 This is String 3 Variable a Variable b Variable int Variable double Variable double Variable int 

설명

  • 정수 값을 char 버퍼에 쓰고 싶다는 것을 올바르게 이해 했습니까? snprintf(). 또한 myStrings 배열의 범위를 벗어난 메모리에 액세스하기 때문에 예제 코드가 충돌합니다. 출력이 어떻게 표시되어야하는지에 대한 예제를 제공 할 수 있습니까?
  • 타 빠른 답변을 위해 nks. 위의 질문에 편집이 있습니다. 문자 배열이 ' 최선의 방법이 아닐 수도 있습니다. 저는 ' 개선을 위해 열려 있습니다.
  • 그렇게 표로 작성된 데이터가 필요합니까, 아니면 한 줄에 하나의 항목이 괜찮습니까? 그것을 표로 만드는 것은 조금 더 복잡 할 것입니다. 여전히 가능하지만 어렵습니다.
  • 열 이름의 길이가 다르기 때문에 표로 만들어야합니다.

답변

우선 테이블의 데이터 구조를 결정해야합니다. 다양한 장단점이있는 많은 옵션이 있습니다. 여기서는 테이블의 각 항목에 대해 고정 된 너비와 고정 된 수의 열이있는 정적으로 할당 된 테이블을 선택합니다. 힙이나 다른 곳에 할당 된 문자열에 대한 포인터를 사용할 수도 있지만 이것이 가장 간단하다고 생각합니다.

어쨌든 기본적인 문제는 변하지 않습니다. 정수 값을 쓰고 싶습니다. 일부 문자열 버퍼입니다. 여기서는 C 라이브러리 함수 snprintf()를 사용하고 있습니다.이 함수는 printf()와 같습니다. 따라서 여기에서는 간단한 형식 문자열을 사용하고 작동하지 않는 형식 문자열 ( 부동 소수점 .. )에 대한 몇 가지 해결 방법을 사용할 수 있습니다.

코드는 다음과 같습니다.

 #include <Arduino.h> /* A table is a 2 dimensional array of char buffers. The core element is a char buffer of fixed size. The number of columns must be fixed at compile time. Rows can by dynamically added in the structure without having to declare the number of elements. You can declare the number of rows at compile time, but do not need to fill them. Thus you can dynamically add rows to the table. */ #define MAX_ENTRY_SIZE 20 #define NUM_COLUMNS 3 #define COLUMN_PRINT_WIDTH MAX_ENTRY_SIZE char myTable[][NUM_COLUMNS][MAX_ENTRY_SIZE] = { {"Column 1", "Column 2" ,"Column 3"}, //Row 1 {"Variable a", "Variable b", "Variable int"}, //Row 2 {"Variable double", "Variable double" ,"Variable double"}, //Row 1 }; char* get_table_entry(int row, int column) { char* entry = myTable[row][column]; return entry; } void write_int_to_table(int value, int row, int column) { //Get a pointer to where the entry is char* entry = get_table_entry(row, column); //write a new string inside it snprintf(entry, MAX_ENTRY_SIZE, "%d", value); } void write_double_to_table(double value, int row, int column) { //Same as above, different format string.. char* entry = get_table_entry(row, column); //Formatting floats on an Arduino Uno is tricky. %f formatters don"t work (cut out due to size.) //use String API instead String stringFloat(value); const char* cString = stringFloat.c_str(); strncpy(entry, cString, MAX_ENTRY_SIZE); } void print_table() { //Get number of Rows int numRows = sizeof(myTable) / (MAX_ENTRY_SIZE * NUM_COLUMNS); for(int row = 0; row < numRows; row++) { //Print all columns of this row for(int column = 0; column < NUM_COLUMNS; column++) { char* entry = get_table_entry(row, column); Serial.print(entry); //fill with spaces to the right for(unsigned int i=0; i< COLUMN_PRINT_WIDTH - strlen(entry); i++) Serial.print(" "); } Serial.println(); //Table header seperator if(row == 0) Serial.println("============================================"); } } void setup() { Serial.begin(9600); print_table(); } void loop() { int a = random(0, 100); double b = random(0, 100); Serial.print("Will write new values for a = "); Serial.print(a); Serial.print(" and b = "); Serial.println(b); //write these in the second row (first row after header), first and second column. write_int_to_table(a, 1, 0); write_double_to_table(b, 1, 1); //Print table again print_table(); Serial.println(); Serial.println(); delay(5000); }  

두 번의 라운드가 출력을 제공합니다. :

Column 1 Column 2 Column 3 ============================================ Variable a Variable b Variable int Variable double Variable double Variable double Will write new values for a = 7 and b = 49.00 Column 1 Column 2 Column 3 ============================================ 7 49.00 Variable int Variable double Variable double Variable double 

댓글

  • 와, 매우 인상적입니다.이 코드에 감사드립니다. 조금만 질문, 테이블 헤드 구분자를 테이블 헤드 길이에 자동으로 인쇄하려면 어떻게해야합니까?
  • int num = NUM_COLUMNS * MAX_ENTRY_SIZE 그런 다음 0에서 iv id =까지의 for 루프에 구분 문자를 인쇄합니다. “c3785e7e9f”>

.

답글 남기기

이메일 주소를 발행하지 않을 것입니다. 필수 항목은 *(으)로 표시합니다