Listing 1: Demonstrates trouble using cin.get


// reversit.cpp   use cin.get(),
// reverse spelling of a word or phrase.
//#define STDIO

#include <string.h>
#ifdef STDIO
#include <stdio.h>
#else
#include <iostream.h>
#endif

// prototype
void reversit(char[]);
// prototype
void swapchar(char *cp1, char *cp2);

// max string length
const int MAX=80;
// global for watching in debug mode
char str[MAX];

int main(void)
{
    char yesno;
    const char *prompt =
       "\nEnter a word or a phrase to \
reverse:\n"; do { str[0] = '\0'; #ifdef STDIO printf(prompt); gets(str); #else cout << prompt; // read in phrase, // include blanks. cin.get(str, MAX); #endif reversit(str); #ifdef STDIO printf("\nThe reverse is:\n%s\n "\nDo another? y/n", str); yesno = getchar(); // discard ALL characters // in buffer fflush(stdin); #else cout << "\nThe reverse is:\n" << str << "\n\nDo another? y/n"; cin >> yesno; // discard ONE character cin.ignore(); #endif } while (yesno == 'y'); return (0); } // function to reverse string void reversit(char s[]) { // index of last character (not \0) int j = (strlen(s)-1); // nothing to do if strlen == 0 if (j<0) return; for (int i = 0; i <= j/2; i++) swapchar(&s[i], &s[j-i]); } //function to swap characters void swapchar(char *cp1, char *cp2) { char temp = *cp1; *cp1 = *cp2; *cp2 = temp; } // end of reversit.cpp //End of File