C++ Help

G

gambler

Guest
Ok so here's the thing i've written two snippets for a program that is supposed to ask the user to input a string then prints the string backwards, It's also supposed to convert all uppercase letters to lowercase and all lowercase letters to uppercase. Any idea, how I can make this whole? (I've been trying for days!!!)

Here's the reversing part:

#include <iostream>
#include <string>

const int LINE_SIZE = 20;
using namespace std;

int main()
{
string correct_word;
char temp_word[LINE_SIZE+1];
int i, j;
cout << "Please enter word to be reversed: ";
cout.flush();
cin >> correct_word;
cin >>

/* correct for the '\0' from the read string */
j = correct_word.size() -1;
for(i = 0; j >= 0; )
temp_word[i++] = correct_word[j--];

/* make sure reversed word isn't ending in garbadge */

temp_word = '\0';
string reverse_word(temp_word);
cout << "Read word was: " << correct_word << endl;
cout << "Reversed word: " << reverse_word << endl;
return 0;
}

And here's the snippet for converting the "cases":

char ch;
cout<<"Enter a character: ";
cin>> ch;

if ( isalpha ( ch ) ) {
if ( isupper ( ch ) )
cout<<"The lower case equivalent is "<< static_cast<char> ( tolower ( ch ) ) <<endl;
else
cout<<"The upper case equivalent is "<< static_cast<char> ( toupper ( ch ) ) <<endl;
}
else
cout<<"The character is not a letter"<<endl;

// Flush the input stream
while ( cin.get ( ch ) && ch != '\n' )
;

cin.get();

I'm having trouble figuring out how I could go through each position of the string and reverse it then check it's position before I output it~ get my drift? Any help will do! Thanks
 
I just wrote this up in a couple of minutes, there's probably a quicker way but I'm too lazy to find it.

Code:
#include <iostream>
#include <string>

using namespace std;

int main()
{
	string str1;

	cout << "Enter string to be reversed: " << endl;
	getline(cin, str1);

	cout << "Original String " << str1 << endl
		 << "Reversed String " ;

	for(int i = str1.size() - 1; i >= 0; --i)
		cout << str1[i];

	string str2(str1);

	cout << "Converting cases: " << endl;

	for(int i = 0; i < str1.size(); ++i)
	{
		if(isupper(str1[i]))
			str2[i] = tolower(str1[i]);
		else
			str2[i] = toupper(str1[i]);
	}
	

	cout << "Original " << str1 << endl
		 << "Inversed " << str2 << endl << endl;

	return 0;
}

if you wanted to include the isalpha() check you could just add that into the for loop.

i.e.
Code:
if(isalpha(str[i]))
  if(isupper(str[i]))
     ...
 
yeah I wanted to input the isalpha(), Got it done Thank you!
 
Back
Top