string lengths as integers.

C

Chris Schumacher

I've been trying to use the following line of code to take a character
from the end of the string:

char b = pStr.substr(pStr.length, 1);

However the compiler (the Visual C++ one) returns the following error:
'substr' : cannot convert parameter 1 from 'unsigned int
(void) const' to 'unsigned int' Conversion is a valid
standard conversion, which can be performed implicitly or by
use of static_cast, C-style cast or function-style cast

I tried static_casting, C-Style and function-style to assign an int
variable the value of the string length, but I got the exact same
error every time.
I also tried use strlen(pStr) and got a similar error (only the data
type of the original was different).

Is there any way to make this work?
Any help is greatly appreciated!

-==Kensu==-
 
I

Ivan Vecerina

Chris Schumacher said:
I've been trying to use the following line of code to take a character
from the end of the string:

char b = pStr.substr(pStr.length, 1);
1) Did you mean:
pStr.length()
?
std::string::length is a member function, not a data member.

2) in C++, char is not equivalent to a 1-character string.
To get the n-th character of a string, you need to
use the [] operator instead of substr.
And character indexes are 0-based, so the last character
is at position length()-1 :
char b = pStr[ pStr.length()-1 ];


hth
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,045
Latest member
DRCM

Latest Threads

Top