View unanswered posts | View active topics It is currently Sat Oct 25, 2014 12:31 am






Reply to topic  [ 5 posts ] 
Accessing individual string characters 
Author Message
Rookie

Joined: Tue Jul 03, 2012 5:16 am
Posts: 43
Post Accessing individual string characters
Hi,

I have always been able to access individuals characters in a string in c++ like this.

string str = "hello";
char c = str[2];

However, when I try this in RobotC, it comes up with the error:
**Error**:LValue for '[]' operator must be a pointer
**Error**:'[]' operator requires pointer value on left hand side [2].

How would I do this in RobotC?


Sun Oct 21, 2012 1:43 am
Profile
Guru
User avatar

Joined: Sun Nov 15, 2009 5:46 am
Posts: 1347
Post Re: Accessing individual string characters
Code:
task main()
{
    char str[] = "hello";
    char c = str[2];
    nxtDisplayTextLine(0, "c=%c", c);
}


Sun Oct 21, 2012 6:33 am
Profile
Rookie

Joined: Tue Jul 03, 2012 5:16 am
Posts: 43
Post Re: Accessing individual string characters
Thanks.

So just don't use the "string" type but an array of chars.
I did it in the end by copying the string into an array using memcpy.


Sun Oct 21, 2012 7:00 pm
Profile
Guru
User avatar

Joined: Sun Nov 15, 2009 5:46 am
Posts: 1347
Post Re: Accessing individual string characters
I don't really understand nor am interested in how string in RobotC works now that it supports pointer syntax. So yes, just use array of char and forget about string. Note that if I recall correctly, string is only good for up to 19 characters anyway. So I don't see any good reason to use string at all. In fact, I think the only reason string still exist in RobotC is for backward compatibility.


Sun Oct 21, 2012 11:42 pm
Profile
Site Admin
Site Admin

Joined: Wed Jan 24, 2007 10:42 am
Posts: 613
Post Re: Accessing individual string characters
That pretty much sums it up - We like the character arrays much more than Strings, but so many people are used to the old implementation so we've worked (much to our pain) to make sure everything will work with both Char Arrays and Strings.

_________________
Timothy Friez
ROBOTC Developer - SW Engineer
tfriez@robotc.net


Thu Oct 25, 2012 12:29 pm
Profile
Display posts from previous:  Sort by  
Reply to topic   [ 5 posts ] 

Who is online

Users browsing this forum: No registered users and 2 guests


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Search for:
Jump to:  



Powered by phpBB © 2000, 2002, 2005, 2007 phpBB Group.
Designed by ST Software for PTF.