Hello, I have this program that runs in C++ that I need to run in C.

This is my program in C++:

#include <iostream>
#include <string>
#include <cctype>
using namespace std;

char encode (char plaintext) {
   if (isupper(plaintext)) {
      if (plaintext > 'M') {
         plaintext += 13;
      }
      else {
         plaintext -= 13;
      }
   }
   else if (islower(plaintext)) {
      if (plaintext > 'm') {
         plaintext +=13;
      }
      else {
         plaintext -=13;
      }
   }
   return (plaintext);
}

int main() {
   cout << "Input string: ";
   string str;
   getline (cin, str);
   for (int i=0; i<string.length();i++) {
      cout << encode(str[i]);
   }
   cout << "\nPress any <ENTER> to exit";
   cin.get();
   return 0;
}

Help would be greatly appreciated

The only C++isms you've got are in main and revolve around string I/O. Basically just replace getline() with fgets() and modify the rest of the code to match.

commented: Thanks, I'll give that a go. +0

you also need to replace iostream with stdio.h, add .h extension to the other includes, delete like 4, and replace cout with printf()

With reference to ur query,
i think u need to manually to change the source code to c by changing header files, printing and reading statements,etc.

You may like to try this C 'readLine' emulation of C++ 'getline' ...

/* CppToC_via_readLine.h.c */

/* using readLine to emulate C++ getline ... */

#include "readLine.h"

/* get copy of file: "readLine.h" at this next link  ... */

/*
  http://developers-heaven.net/forum/index.php/topic,2580.msg2864.html#msg2864

*/

char encode( char plaintext )
{
    if( isupper(plaintext) )
    {
        if( plaintext > 'M' ) plaintext += 13;
        else plaintext -= 13;
    }
    else if( islower(plaintext) )
    {
        if( plaintext > 'm' ) plaintext +=13;
        else plaintext -=13;
    }
    return plaintext;
}


int main()
{
    char* str;
    unsigned i;

    printf( "Input string: " ); fflush( stdout );

    str = readLine( stdin ); /*free dynamic memory*/

    for( i = 0; i < strlen( str ); ++ i )
        printf( "%c", encode( str[i] ) );

    free( str ); /*now can free dynamic memory*/

    printf( "\n\nPress any <ENTER> to exit ... " );
    getchar();
    return 0;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.