I am kind of a beginner in C++,started learning the language this year at university.
The next day I have an exam.One of the problems that needs to be solved with C++ includes a making a program that by entering a any word(Ex.:"Table")would reverse it,so it would look like :"Elbat".
I seem to have found some reasonable solutions on the net,but the problem is that it included stuff that i haven't learned yet,like Vectors and some else.
Now i would like someone to help me find solution to my problem.All i know is that commands like: .length and .at should be used.
I would appreciate any help,thanks in advance.

>> would appreciate any help,thanks in advance
Post the code you have written so far. If all you have to do is display the reversed string on the screen then create a loop that starts at the end of the string and decrement the loop counter until it reaches 0, something like this. Use cout to display the character.

let counter = string length - 1
while counter >= 0
   display one character of the string
   decrement counter
end while

If you are required to use std::strings, I'll give you a hint:

#include <iostream>
#include <string>

using namespace std;

int main()
{

	string str = "abc";
	cout << str[0] << endl;
	cin.get();

	return 0;
}

Now if you combine this with a loop and .length, you should be able to come to an answer!

[edit]Darn, too slow again...[/edit]

Edited 5 Years Ago by Nick Evan: n/a

The code i have written so far is:

#include <iostream>
#include <string>
#include <iomanip>

using namespace std;

int main()
{
    string word,reverse;
    int i,x,j;
    cout<<"Enther a word"<<endl;
    cin>>word;
    i=zbor.length();
    j=i;
    while(i!=0)
    {
               for(x=1;x<=j;x++)
               reverse.at(x)=word.at(i);
               i--;
    }
    cout<<reverse<<endl;
    system("pause");
    return 0;
}

Excuse me if my code sucks,but i am almost a tottal beginner

Edited 5 Years Ago by Nick Evan: n/a

You were allmost there, but you're thinking too complicated:
(I've changed original code slightly, it could still be optimized)

#include <iostream>
#include <string>

using namespace std;

int main()
{
	string word,reverse;
	int i;
	cout<<"Enter a word"<<endl;
	cin >> word;
	i=word.length();
	
	while(i>=0)
	{
		cout << word[i]; 
		i--;
	}
	cout<<endl;
	cin.ignore();
	cin.get();
	return 0;
}

cin.get() only takes in 1 char, so I've replaced it. Then in your loop I'm justing printing the characters in reverse order. No buffer needed!

ps. Next time you post code, please use code tags and indention, it makes your code easier to read.
Also never use system("pause"); If you ever want to run this program on Linux (or BSD/MAC etc) it will just give an error

Edited 5 Years Ago by Nick Evan: n/a

Thanks master!!!
This seems to be working 100% and it's written very simple,thank you very much :)

This article has been dead for over six months. Start a new discussion instead.