English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

//program to arrange the string in decending order
#include
#include
#include
#include
class des {
private:char ch[35],temp;
int len;
public: int get();
int sort(int);
int print(int);
};
int des::get()
{
cout<<"neter the st: ";
gets(ch);
len=strlen(ch);
return len;
}
int des::sort(int i)
{
for(int j=0;j { for(int k=j+1;k {
if(ch[j] { temp=ch[j];
ch[j]=ch[k];
ch[k]=temp;
}
}
}
return i;
}
int des::print(int p)
{
for(int m=0;m { cout< return 0;
}
void main()
{ clrscr();
des hi;
int a=0,b=0,c=0;
a=hi.get();
b=hi.sort(a);
hi.print(b);
getch();
}

2007-02-23 23:11:34 · 2 answers · asked by simran m 1 in Computers & Internet Programming & Design

2 answers

Well here is a better version of your code:

#include
#include
#include

using namespace std;

int main (void)
{
string str;
cout << "Enter a string\t\t=> ";
getline(cin, str);
cout << "The reversed string is\t=> ";
for (string::reverse_iterator i = str.rbegin(); i != str.rend(); ++i)
cout << *i;
cout << endl;
system("pause");
return EXIT_SUCCESS;
}

If you are using C++ and not C, then you should use the C++ Standard String Library. In addition, your code is not ANSI C++ since it uses the Borland Conio Library; if you are under Windows, then simply you can use under the stdlib library the function system("pause") instead of getch().
Remember that now under ANSI C++ using namespace std is the preferred way to do things. Finally as you can see the String Library uses the advanced features of STL including the reverse iterators. In our case we used the reverse_iterator specifying it to to start the traversal from the rbegin (synonym for "start at the end of the string") and end till the beginning of the string. It's important to realize that the string is NOT yet really reversed, we only displayed it in reversed order.
To actually reverse it in such the indexes are really changed rather than just displaying it in reversed order, then perhaps this is one of the ways:

#include
#include
#include

using namespace std;

void reverse_string(string&);

int main (void)
{
string str;
cout << "Enter a string\t\t=> ";
getline(cin, str);
cout << "The reversed string is\t=> ";
reverse_string(str);
cout << str << endl;
system("pause");
return EXIT_SUCCESS;
}

void reverse_string(string& str)
{
string temp = "";
for (string::reverse_iterator i = str.rbegin(); i != str.rend(); ++i)
temp += *i;
str = temp;
return;
}

Hope it's helpful :-)

Regards

Coosa

2007-02-24 00:57:55 · answer #1 · answered by Coosa 2 · 0 0

Actually the problem in the logic. Try to modify it.

2007-02-24 08:53:54 · answer #2 · answered by sridhar b 2 · 0 0

fedest.com, questions and answers