Any tips as to why my program isn't working?

The program is supposed to output a sentence backwards that is input by the user using a function.. here's what I've got:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <cstring>
#include <string>
using namespace std;


void doit(char N[255], char temp, int lettercount, int lettercount2);
int main(){
  char sentence[255];
  char temp =0;
  int lettercount;
  int lettercount2;

  cout << "Please input a sentence." << endl;
  cin.getline(sentence, 255);
  lettercount = strlen(sentence);
  lettercount2 = lettercount;

  doit(sentence, temp, lettercount, lettercount2);
  cout << "the sentence in reverse is" << endl;
  cout << sentence;
}

void doit(char sentence[255], char temp, int lettercount, int lettercount2) {
  for(int i=0; i < lettercount2; i++){
    temp == sentence[i];
    sentence[i] == sentence[lettercount];
    sentence[lettercount] == temp;
    lettercount--;


I know its an ugly way to approach it but I can't see why it's not working, any ideas?
1
2
3
4
5
6
void doit(char sentence[255], char temp, int lettercount, int lettercount2) {
  for(int i=0; i < lettercount2; i++){
    temp == sentence[i];
    sentence[i] == sentence[lettercount];
    sentence[lettercount] == temp;
    lettercount--;


Should be:

1
2
3
4
5
6
void doit(char sentence[255], char temp, int lettercount, int lettercount2) {
  for(int i=0; i < lettercount2; i++){
    temp = sentence[i];
    sentence[i] = sentence[lettercount];
    sentence[lettercount] = temp;
    lettercount--;


The double equal sign tests whether both the left and right values are equal, and returns true if they do. In this case, you wanted to use the assignment operator, which assigns the value to the right of the operator to the variable to the left.
Hey thanks for the tip; but what it's doing now is assigning nothing to "sentence" whereas before it would just cout the same sentence without changing anything.
To output a sentence backwards does not mean that the sentence itself shall be reversed.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <cstring>

void reverse_output( const char *sentence, std::ostream &os = std::cout )
{
   size_t n = std::strlen( sentence );

   while ( n ) os << sentence[--n];
}

int main()
{
   const size_t N = 255;
   char sentence[N];

   std::cout << "Please input a sentence: ";
   std::cin.getline( sentence, N );

   reverse_output( sentence );

   return 0;
}
Last edited on
Topic archived. No new replies allowed.