Hi, I'm trying to write a program that accepts a string (a line, sentence, or phrase) and then the program has to display the contents of that string backward. for example, if I entered "starting out" the program has to convert it to "tuo gnitrats".
This is my code. But I don't know what's wrong with it.
I don't think you should pass sentence pointer in and then declare it again. Try taking off the 'char' in your backwards function. Also, where the heck is 'set' declared? What is it?
Ok
I don't know why I used "set." I'm looking at the examples in my book and just kinda finding my way around. It's trial and error for me, guys. I guess I was trying to give the array a name so that the computer knows how many characters it has and works backward from there...ignore this. I don't know what I was doing.
anyway,
from the suggestions, I recode it:
//write a function that accepts a pointer to a C-string as an argument and displays its contents backwards.
#include <iostream>
usingnamespace std;
//function Prototype
void Backward (char *);
int main ()
{
char line[201];
cout << "This program will display the contents of the entered phrase backward.\n";
cout << "Please enter a phrase of no more than 200 characters, followed by a period.\n";
cin >> line;
cout << "The entered string displayed backward: \n";
cout << Backward(line) << endl;
}
void Backward (char *sentencePtr)
{
char *p = sentencePtr;
while( *p != '\0')
++p;
while( p != sentencePtr )
cout.put( *--p );
}
and I got the following error:
X:\dtran5.pds\Chapter 10 HWa\Project #2 backward string.cpp(20) : error C2679: binary '<<' : no operator defined which takes a right-hand operand of type 'void' (or there is no acceptable conversion)
You're calling backward out of context.
It doesn't return anything (It's void backward(char*)), so you can't get anything out of it. What you need to do is just print out the modified array.
Be careful, the way Narue's written it, it will automatically output the letters, so you can't just leave in your original cout.
Just call backward(line) after you say "The line printed backwards:"
Ok, I fixed that. And the problem right now is that the program only shows invert the first word of the sentence and disregards the rest of the sentence.
>cin >> line;
You had it right the first time, when you were using getline. cin's >> operator stops reading at whitespace, so line only contains the first word.
No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.