Hello everyone! New here and starting to learn programming recently. I decided to start with C++ despite the difficulty / flexibility. Anyway, I went through every tutorial on this site, writing practice programs along with it.
Now I'm reading a book called Learning C++ Through Game Programming. Unfortunately it doesn't go by C++11 like your site does, so I'm wondering if there is a more efficient way of coding this regardless.
There's an exercise that says to write a program that uses pointers and gets the size of a string. My code is below. It runs and compiles without any error but I'm not exactly sure if I'm even using pointers correctly either. If there's any other or more efficient way of coding it, please let me know.
#include <iostream>
#include <string>
usingnamespace std;
// this is passby reference, it looks better than passby pointer. use const as much as you can
void getStrSize(const string & sName); // function for getting string size
int main()
{
std::string str;
cout << "Enter a string to get it's size: ";
getline(cin, str);
getStrSize(str);
cin.get(); // requires entering of a key to close program
return 0;
}
void getStrSize(const string & sName)
{
cout << sName.size();
}
Thanks to the both of you for your tips. I didn't realize you could declare variables within functions. Very handy to know.
As for littlepig, that's probably how I would have programmed it normally, but the exercise in the book specifically said I had to use pointers. But nonetheless, thank you for posting that!