hi i am trying to do a program that will output a string in revers, more like a word, like, (string too gnirts), with user input. i have done a quick program that reverse a string without user input. please help. thank you.
#include <iostream>
usingnamespace std;
string* copy(string* arr, int size)
{
string * result = new string[size];
for (int x = 0; x < size; x++)
{
result[x] = arr[size - 1 - x];
}
return result;
}
string* create( void )
{
string *ret = new string[3];
ret[0] = "A"; // which I am not sure will work without that #include <string>
ret[1] = "B";
ret[2] = "C";
return ret;
}
int main()
{
string* list = create();
string* other_list = copy(list, 3);
for (int x = 0; x < 3; x++)
{
cout << other_list[x] << endl;
}
delete [] list; // make sure to have [] when you delete an array
delete [] other_list;
}
Your program should function the same way. The extraction hasn't done much code wise, but it did isolate the place in the code where you will get user information.
There are two general methods to do this with a dynamic array:
1 2 3 4
create a non-dynamic array that is larger than the expected input amount
for every word the user types, add the word to the array and keep track of amount
create a dynamic array the size that you counted
copy the large array into the correctly sized one and return the correctly sized one
1 2 3 4
capture the entire line into one string
count the words in the string
create a dynamic array the correct size
copy words from the line into the array and return the array
But it's much quicker to use std::vector< std::string>. In fact, the whole program takes two lines.
we have not gone over vectors, just up to strings and pointers. with the string and cstrings libraries so i will feel more comfortable staying in between what i have learned so far.
by the way the code, is an example of reversing an array. i want to reverse a word. and not a string,.
Program Input
Standard Input
hello
Program Output
Enter some word
olleh
Program Output (Character-by-Character)
E n t e r s o m e w o r d \n
o l l e h \n
this is the homework question. i need help doing this,
ok i solved it, but now when i run the test cases, it saying that i am missing the "\n" at the end of the reversed word, right now i have ";" at the end and i have tried endl; as well but that just skips to the next line after each character.
#include <iostream>
#include <cstring>
usingnamespace std;
int main()
{
char words[100];
int x, i;
cout<< "Enter some word" << endl;
cin>> words;
x = strlen(words);
//This two line is used to reverse the string
for(int i = x; i > 0; i--)
{
cout<< words[i - 1];
}
return 0;
}