gr33kbo1
gr33kbo1

Reputation: 309

Why doesn't myString.at(myString.length()) work?

I'm including the <string> library at the top of my .cpp file but when I test it out

 cout<<myString.at(myString.length());

It should print out the last letter of the string, or at least I think it should. But my compiler throws a hissy fit and spits back a bunch of jargon at me.

I'm used to writing in JavaScript so I'm not used to, well....having rules, so to me this makes perfect sense to return the last character of the string.

Upvotes: 0

Views: 1113

Answers (5)

nook
nook

Reputation: 2396

Since we start counting at zero, you need the length - 1 to get the last character.

std::cout << myString.at(myString.length()-1) << std::endl;

Upvotes: 0

DhruvPathak
DhruvPathak

Reputation: 43245

it should be

cout <<myString.at(myString.length()-1 );

as string indexes are 0 based, hence a string "hello" will have indexes from 0 to 4, and a length of 5.

#include <string>
#include <iostream>

using namespace std;

int main(){
  string myString = "hello";
  cout << myString.at(myString.length()-1 ); //outputs "o"

}

demo : http://codepad.org/QxwrjpIt

Upvotes: 2

Martin Perry
Martin Perry

Reputation: 9527

Because string is indexed as array... position at length() is out of bounds.

You should use length() - 1

Full example: cout << myString.at(myString.length() - 1);

Upvotes: 0

P0W
P0W

Reputation: 47814

Did you include namespace std ?

Also it should be 1 less than the length to account for zero-based indexing

std::cout<<myString.at(myString.length()-1);

Upvotes: 1

simonc
simonc

Reputation: 42185

String indexes are zero-based so run [0..myString.length()-1]. You should use

myString.at(myString.length()-1);

to get the last character

Upvotes: 7

Related Questions