String Manipulation Question

Go To Last Post
5 posts / 0 new
Author
Message
#1
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

I am having a problem getting what I expect from this code segment

#define asciibufsize 100

char asciibuf[asciibufsize];//ASCII buffer for data return message
char d = 'd';// Single d character
char space = ' ';

//I initialized asciibuf to all zeros

strcat(asciibuf, &d);// put 'd' prefix on each datasegment
itoa(i,asciinum);// Create ASCII number sequence for data value
strcat(asciibuf, asciinum);// Put the channel number after the prefix
strcat(asciibuf, &space); // Insert a space before value

When "strcat(asciibuf, &d);// put 'd' prefix on each datasegment" gets executed I expect my asciibuf to have "d" what it actually has is "d ". It seems to have an additional space in there after the d. Anyone know how I can get "d" without the space?

Thanks,

Erick

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

strcat() appends a NULL terminated string to a buffer.
the variable 'd' is simply a byte. strcat() will start with the 'd' in the var d and continue copying characters from the following memory locations until it finds a NULL.

A simple fix is to declare d as follows:
char *d = "d";
.
.
.
strcat(asciibuf, d);

should work OK.

or
// memset(asciibuf, 0, sizeof(asciibuf)); // <= not needed
asciibuf[0] = 'd';
itoa(i, &asciibug[1], 10) // <=10 is radix for conversion
strcat(asciibuf, " ");

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

I tried putting your code into DOS turbo C, and things got screwy because the "asciibuf" array wasn't getting initialized. I worked around this by either saying:

char asciibuf[100]="" //upon initialization

or

asciibuf[0]=NULL; //before writting to it.

Perhaps it is an init problem.

Good Luck,
Paul

admin's test signature
 

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Paul,

I did initialize it earlier in code. I just didn't include that in the posted fragment. Thats why I inserted the comment that it was previously initialized.

I ended up getting around the problem by using a different fucntion call
strncat(asciibuf, &d, 1);

where the 1 at the end says only concantenate 1 value from &d into asciibuf.

Thanks to both of you.

Erick

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Opps! Sorry, I missed that comment. It seemed to work ok in TurboC. What compiler are you using?

admin's test signature