954,500 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Copying only part of a character sequence

I am trying to copy the first three characters of a character array into another character array of length 3.

For instance, if I use

char trig [10] = "cos(50)"; //declare and assign the char array "trig"
char t [3]; //declare char array t to store the "cos" part of the trig array

t[0] = trig[0];
t[1] = trig[1];
t[2] = trig[2];

Whenever I do this, I get 0012FF48 as a result. But of course I was expecting "cos". What's the deal?

ShellB12
Newbie Poster
7 posts since Jun 2008
Reputation Points: 10
Solved Threads: 0
 

You are missing the null terminator at the end, but that shoulden't explain why its outputting the address of t . The correct way to do it would be like this:

char trig [10] = "cos(50)"; //declare and assign the char array "trig"
char t [4]; //declare char array t to store the "cos" part of the trig array

t[0] = trig[0];
t[1] = trig[1];
t[2] = trig[2];
t[3] = '\0';

Try that and see if it works

William Hemsworth
Posting Virtuoso
1,591 posts since Mar 2008
Reputation Points: 1,429
Solved Threads: 129
 

Nope. It didnt work. Still gives me the t address.

Before I tried using a pointer as an intermediary beten trig and t... it sorta worked. I got something like

cos[[[[[]]]8someweirdshit***&

ShellB12
Newbie Poster
7 posts since Jun 2008
Reputation Points: 10
Solved Threads: 0
 

Well, I compiled the code and it worked perfectly for me, so mabey its something to do with your compiler settings.

William Hemsworth
Posting Virtuoso
1,591 posts since Mar 2008
Reputation Points: 1,429
Solved Threads: 129
 

I'm using the free version of visual c++. The "Express" edition. They did say that it didnt have all the bells and whistles of the regular version.

But i dunno. Thanks tho.

ShellB12
Newbie Poster
7 posts since Jun 2008
Reputation Points: 10
Solved Threads: 0
 

Could you post the exact code your using ?

Nick Evan
Not a Llama
Moderator
10,112 posts since Oct 2006
Reputation Points: 4,142
Solved Threads: 403
 

OMG, williamhelmswort's suggestion worked!

The problem was that I had too many preprocessor directives up?? I took out the unncecessary ones and it worked!

Thanks guys.

ShellB12
Newbie Poster
7 posts since Jun 2008
Reputation Points: 10
Solved Threads: 0
 

That's a long winded way of doing it:

Other options include using std::strings and relevant functions such as substr()

And other c-style string functions...

iamthwee
Posting Expert
5,950 posts since Aug 2005
Reputation Points: 1,543
Solved Threads: 439
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You