| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Display Modes |
|
#1
|
|||
|
|||
|
Send characters from a string in reverse order to output window
I am taking my first programming class and part of our HW is this:
Write, debug and run a C++ program that prompts the user to enter a string; reads the string and sends the characters to the output window in reverse order; thereby reversing the string. this is what I have : #include <iostream> #include <string> using namespace std; int main () { string message; do; { cout << "Enter a string:\n"; getline(cin, message); } while ( message.length() == 0 ); return 0; } I have no idea how to send the characters to the output window in reverse order |
|
#2
|
|||
|
|||
|
Just use a for loop starting from the end of the string and counting to the beginning, like this:
for (int i = LEN - 1; i >=0; i --) { std::cout << szString[i]; } How to find the length of the string I leave to you ![]() |
|
#3
|
|||
|
|||
|
Quote:
im still very new to programming and what you have told me helps alot I still need more help, The book my school uses is not answering my questions. I can find the length, but like I dont know why you put the " std:: " and just in general i dont know how to finish this program properly |
|
#4
|
||||
|
||||
|
Code:
#include <cstdlib>
#include <iostream>
using namespace std;
int main ()
{
string choose;
cout<<"Write Something\n";
getline(cin,choose);
for(int i = choose.length()-1;i>=0;i--)
/*The for statement has three arguments in order to accomplish this task
1] int i = choose.length()-1 gets the length of the string and subtracts
the null character so you dont get a blank space in the return
try it both ways to see what i mean
2] i greater than zero to terminate loop is self explanatory.
3] i-- counts backwards to give the desired affect.
*/
{
cout<<choose[i];/*since a string is basically an array of characters
you can use them as such, so i is now the length of your string and
every time the loop processes it subtracts one */
}
system("PAUSE");
return 0;
}
The std:: is used if you dont use "using namespace std" which just makes the std a namespace so you can use cout and cin instead of typing std::cout every time. Looks like you have most of the stuff down just not your loops, might want to look into practicing a little more with those. Hope this explanation helps ya a little. Most people dont like responding to homework but it looks like you atleast made an attempt. ![]()
__________________
---Official Member Of The Itsacon Fan Club--- ![]() Give a man a fish and he will eat for a day. Teach a man to fish and he will sit in a boat all day drinking beer. |
![]() |
| Viewing: Dev Articles Community Forums > Programming > C/C++ Help > Send characters from a string in reverse order to output window |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|