The complete question is : 12. Write a function printVertically that takes a parameter of type string and displays the string of characters vertically. The function does not return anything to main. Write main to test this function. Use of array is not allowed.
My doubt is : What approach can be used to display characters in a string vertically without using array? Remaining Part of question I have understood and will do myself.
#include <string>
// Write a function printVertically that takes a parameter of type string and displays the string of characters vertically.
void printVertically( const std::string& str ) { for( char c : str ) std::cout << c << '\n' ; }
I'm always a bit befuddled by responses like "I don't want to use <API>" when assignment says "I must use library object with <API>".
You are asked to use a std::string, not an array. std::string.length() is part of std::string's public interface; you have absolutely no reason not to.
Here's the kicker: a std::string is a fancy thing that manages an array of characters for you. So you can index it just like a normal array. Conveniently, it also provides you with methods to track how long the array is.
Compare:
1 2 3 4 5
void display_vertically( constchar* s, int length )
{
for (int n = 0; n < length; n++)
...
}
1 2 3 4 5
void display_vertically( std::string s )
{
for (int n = 0; n < s.length(); n++)
...
}
Life is easy.
What the first example leaves out is all the effort you had to go to in main() to create and populate and free the char array. The second example relieves you of that.
1 2 3 4 5 6 7 8
int main()
{
cout << "Hey, enter a string: ";
string s;
getline( cin, s );
display_vertically( s );
}
Sweet!
tl;dr: use the tools given to you; don't look for reasons not to use them.
Ok,
1. Some part of string API has been covered.
2. You have to use string.
The obvious followup question is: What bits of string API has been covered?
Depending on that answer there are multiple scenarios. For example,
* The already covered API is sufficient.
* The covered API is not enough, but student is expected to read ahead.
* The API was covered, but forgotten.
* ...
Even after it is covered in class; strongly favour using a a range based loop for simple loops like this. Resort to the classical for loop only when there is a more complex requirement.