Carriage returns in arrays

I am using the following code

char str[50];
char fstr[10];
int a0 = 247;

strcpy(str,"");
strcat(str,"sd1, "); dtostrf(a0,0,0,fstr); strcat(str,fstr);

to produce an output;
sd1, 247

but what I really want is several pieces of data, separated by a CR, and achieve an output of;

sd1, 247
sd2, 423
sd3, 21

This represents csv data for updating a website.
Can this be achieved within an array, or do I need a number of arrays with CR's between?
Last edited on
std::stringstream is very useful for converting between strings and numerical data.

http://www.cplusplus.com/reference/iostream/stringstream/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
#include <string>
#include <sstream>

int main()
{
     const int NUM_DATA = 3;
     int data[] = {247, 423, 21};

     //stores the result
     std::ostringstream result;

     //used for converting numbers to strings
     std::stringstream numConverter;

     //used for storing the string conversions (to be placed in the result)
     std::string temp;

     for(int i = 0; i < NUM_DATA; i++)
     {
          if( i != 0 )
          {
               result << "\r\n"; //carriage return after previous line
          }

          result << "sd";

          //convert the number after "sd" into a string and append to the result
          numConverter << (i + 1) << " "; //appending a space to be able to reuse numConverter
          numConverter >> temp;
          result << temp;

          result << ", ";

          //convert the piece of data into a string and append to the result
          numConverter << data[ i ] << " ";
          numConverter >> temp;
          result << temp;
     }

     std::cout << result.str() << std::endl;

     return 0;
}
sd1, 247
sd2, 423
sd3, 21
...except that std::stringstream is C++, and the OP appears to be using C.

Simply strcat( str, "\n" ); to add a carriage return. You can print it normally with [f|s]printf():

printf( "%s", str );

Hope this helps.
Topic archived. No new replies allowed.