3 Replies - 222 Views - Last Post: 18 August 2019 - 10:14 PM Rate Topic: -----

#1 beginnerC++   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 9
  • Joined: 14-August 19

CLASS STRING

Posted 17 August 2019 - 09:26 PM

I just want to say thank you for helping me. You guys are amazing.
...So, moving onto class string, i have been reading about it and i decided to write a simple code for an example i saw in the book. The program runs, however i got stuck at the end and i had to go back and kind of "cheat" and see how the book solved it. Everything i did made sense except for this : << firstname.at(0) << lastname.at (0) <<endl;

My question is, why did the book use .at(0) ? i don't get it and the book does not say why.

Here is my code:
#include <iostream>
#include <string>
 using namespace std;
 int main( )
{
    string firstname, lastname;
    string wholename;
    string greeting = " Hello ";

    cout<<"Enter your first name"<<endl;
    cin>>firstname;
    cout<<"Enter your last name"<<endl;
    cin>>lastname;

    wholename = firstname + " " +lastname;

    cout<<greeting<<wholename<<'!'<<endl;


    cout<<"YOUR INITIALS ARE: " << firstname.at(0) << lastname.at (0) <<endl;

    return 0;
}



I did everything but i had to copy the last part from the book because it was not running. Thanks for the feedback.

This post has been edited by ndc85430: 18 August 2019 - 12:39 AM


Is This A Good Question/Topic? 0
  • +

Replies To: CLASS STRING

#2 ndc85430   User is offline

  • I think you'll find it's "Dr"
  • member icon

Reputation: 979
  • View blog
  • Posts: 3,858
  • Joined: 13-June 14

Re: CLASS STRING

Posted 17 August 2019 - 11:08 PM

The alternative, of course, would be to use square brackets (e.g. foo[0]), but at at least does bounds checking (i.e. it will throw an exception if the index is out of bounds). The same is true for at on containers like std::vector or std::array.

Also, please remember to post code within "[CODE]" tags as you're asked. I've done it for you this time.

This post has been edited by ndc85430: 18 August 2019 - 12:40 AM

Was This Post Helpful? 0
  • +
  • -

#3 beginnerC++   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 9
  • Joined: 14-August 19

Re: CLASS STRING

Posted 18 August 2019 - 08:01 PM

@ndc85430 thank you for your feedback. How do i add the tags? i cant find the option
Was This Post Helpful? 0
  • +
  • -

#4 ndc85430   User is offline

  • I think you'll find it's "Dr"
  • member icon

Reputation: 979
  • View blog
  • Posts: 3,858
  • Joined: 13-June 14

Re: CLASS STRING

Posted 18 August 2019 - 10:14 PM

You're told what to do in the box where you type your post. There's also a "[CODE]" button in the editor.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1