2

Some days ago i started a thread. concatenation of non constant character array with a sting

I have a different question but on the same nature (string and chars)

what i want is one variable (string or char) that will hold a standard text and the value of gps coordinates latitude and longitude

The format is this: "latitude/longitude: 30.111111 20.111111"

What i have is a char that holds the standard text and the latitude: "Latitude/Longitude: 30.111111"

I also have another char that holds the second value (longitude)

The chars were generated with dtostrf():

char clat[10 + 20 + 1] = "Latitude/Longitude: ";
char clng[10 + 1];
dtostrf(gps.location.lat(), 10, 6, clat+20);
dtostrf(gps.location.lng(), 10, 6, clng);

I can also make the chars strings:

string1 = String(clat);

What have i tried: 1.Assigning clng to clat directly via dtostrf()

char clat[10 + 20 + 10 + 1] = "Latitude/Longitude: ";
dtostrf(gps.location.lng(), 10, 6, clng+31);

It didnt work and got unexpected output

  1. making clat a string and assign clng via for loop

    string1 = String(clat); for (int i=0; i<10; i++) string1[i+32]=clng[i];

This doesnt append it

I run out of ideas here. Any help from more experienced guys?

user1584421
  • 1,425
  • 3
  • 26
  • 36

2 Answers2

1

solved it. was simple actually. dont know how to do it with chars, but with strings there is the addition operator. So i converted both to string and used the + operator.

char clat[10 + 20 + 1] = "Latitude/Longitude: ";
char clng[10 + 1];
String string1, string2, finalstr;

and inside the loop:

dtostrf(gps.location.lat(), 10, 6, clat+20);
dtostrf(gps.location.lng(), 10, 6, clng);
string1 = String(clat);
string2 = String(clng);
finalstr = string1 + string2;

Maybe that was too much work? If you have any smarter alternatives, please provide!

user1584421
  • 1,425
  • 3
  • 26
  • 36
1

One thing I noticed is you do not need the + in:

char clat[10 + 20 + 1] = "Latitude/Longitude: ";

You can just do this:

char clat[31] = "Latitude/Longitude: ";

A much simpler way to do this is this:

Variables to initialize:

char subfinal[40] = "Latitude/Longitude: ";
String final = ""; //You don't need this, you could always use `String(subfinal)` instead

The code inside a function:

dtostrf(gps.location.lat(), 10, 6, subfinal+10);
subfinal[29] = " ";
dtostrf(gps.location.lng(), 10, 6, subfinal+30);
final = String(subfinal);

I haven't tested it, so let me know if it doesn't work.

Anonymous Penguin
  • 6,365
  • 10
  • 34
  • 62