Page 1 of 2 12 Last
  • Jump to page:
    #1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2013
    Posts
    9
    Rep Power
    0

    I need some help in my project converting c++ to c. can anyone help me?


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

    bool bValid(string sInput2);
    int main() {
    bool bAgain = false;
    do{ //Asks user to input characters. Validates whether the characters are letters of alphabet by calling bValid and passing along the string sInput
    string sInput;
    do{
    cout << "Enter some characters: ";
    cin >> sInput;
    if(!bValid(sInput))
    cout << "Invalid input. Try again (input must be a member of the alphabet).\n\n";
    }
    while(!bValid(sInput));


    int iCount[26]; //iCount[26] is an array for which each index of iCount will hold the number of times each character appeared in your input
    for(int a=0; a<26; a++) {
    iCount[a] = 0;
    }

    int a = 0, iStore = 0;
    string sStore; //sStore is a string to hold any characters that were present in the initial input
    string sCheck = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    bool bCheck = false;

    for (int k=0; k<27; k++) { //This nested for-loop checks all inputted character with each of the valid letters of the alphabet as initialized with string sCheck
    bCheck = false;
    for(int j=0; j<sInput.size(); j++){
    if(sCheck[k] == toupper(sInput[j])) { //toupper makes each inputted character to upper case to avoid having to compare a lowercase letter with an uppercase letter. Example (a != A)? -> true
    sStore[iStore] = sCheck[k];
    iCount[a]++;
    bCheck = true;
    }
    }
    if(bCheck) {
    a++;
    iStore++;
    }
    }

    cout << "\nThe compressed result is: ";
    int j = 0;
    for (a=0; a<iStore; a++) { //outputs the compressed strings of characters
    cout << iCount[a] << sStore[j] << " ";
    j++;
    }
    cout << "\n";

    double dInitial = (double)sInput.size(); //converting sInput.size() to a double
    double dFinal = (double)iStore; //converting iStore to a double
    double bRate = ((2*dFinal)/dInitial);
    cout << "The final string of characters(" << 2*8*iStore << " bits) is: ";
    cout << bRate << " times the size of the intial(" << 8*sInput.size() << " bits).\n\n";

    bool bInvalid = true;
    do{ //Checks if you want to run the program again
    char cAgain;
    cout << "Run program again [Y/n]? ";
    cin >> cAgain;
    if(tolower(cAgain) == 'y'){
    bAgain = true;
    bInvalid = false;
    }
    else if(tolower(cAgain) == 'n'){
    bAgain = false;
    bInvalid = false;
    }
    else{
    cout << "Invalid input, try again.\n\n";
    }
    }
    while(bInvalid);
    }
    while(bAgain);

    return 0;
    }

    bool bValid(string sInput2) {
    int ret = 1;
    string sValid = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    for(int j=0; j<sInput2.size(); j++) {
    int test = 0;
    for(int i=0; i<27; i++) {
    if(toupper(sInput2[j]) == sValid[i]) {
    test = 1;
    break;
    }
    }
    if(test == 0) {
    ret = 0;
    break;
    }
    }
    return ret;
    }
  2. #2
  3. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,255
    Rep Power
    2222
    Unreadable mess! Made even more unreadable by that idiotic K&R indenting style which hides open-braces at the ends of lines and, far worse, in the middle of lines.

    Use code tags! Here is what your code looks like when code tags are used -- original indentation retrieved via the Reply button; you may use it to see what code tags look like:
    Code:
    #include <iostream>
    #include <string>
    using namespace std;
    
    bool bValid(string sInput2);
    int main() {
        bool bAgain = false;
        do{                         //Asks user to input characters. Validates whether the characters are letters of alphabet by calling bValid and passing along the string sInput
            string sInput;
            do{
                cout << "Enter some characters: ";
                cin >> sInput;
                if(!bValid(sInput))
                    cout << "Invalid input. Try again (input must be a member of the alphabet).\n\n";
            }
            while(!bValid(sInput));
    
    
            int iCount[26];         //iCount[26] is an array for which each index of iCount will hold the number of times each character appeared in your input
            for(int a=0; a<26; a++) {
                iCount[a] = 0;
            }
    
            int a = 0, iStore = 0;
            string sStore;        //sStore is a string to hold any characters that were present in the initial input
            string sCheck = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
            bool bCheck = false;
    
            for (int k=0; k<27; k++) {      //This nested for-loop checks all inputted character with each of the valid letters of the alphabet as initialized with string sCheck
                bCheck = false;
                for(int j=0; j<sInput.size(); j++){
                    if(sCheck[k] == toupper(sInput[j])) { //toupper makes each inputted character to upper case to avoid having to compare a lowercase letter with an uppercase letter. Example (a != A)? -> true
                        sStore[iStore] = sCheck[k];
                        iCount[a]++;
                        bCheck = true;
                    }
                }
                if(bCheck) {
                    a++;
                    iStore++;
                }
            }
    
            cout << "\nThe compressed result is: ";
            int j = 0;
            for (a=0; a<iStore; a++) {              //outputs the compressed strings of characters
                cout << iCount[a] << sStore[j] << " ";
                j++;
            }
            cout << "\n";
    
            double dInitial = (double)sInput.size();    //converting sInput.size() to a double
            double dFinal = (double)iStore;             //converting iStore to a double
            double bRate = ((2*dFinal)/dInitial);
            cout << "The final string of characters(" << 2*8*iStore << " bits) is: ";
            cout << bRate << " times the size of the intial(" << 8*sInput.size() << " bits).\n\n";
    
            bool bInvalid = true;
            do{                                      //Checks if you want to run the program again
                char cAgain;
                cout << "Run program again [Y/n]? ";
                cin >> cAgain;
                if(tolower(cAgain) == 'y'){
                    bAgain = true;
                    bInvalid = false;
                }
                else if(tolower(cAgain) == 'n'){
                    bAgain = false;
                    bInvalid = false;
                }
                else{
                    cout << "Invalid input, try again.\n\n";
                }
            }
            while(bInvalid);
        }
        while(bAgain);
    
        return 0;
    }
    
    bool bValid(string sInput2) {
        int ret = 1;
        string sValid = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    
        for(int j=0; j<sInput2.size(); j++) {
            int test = 0;
            for(int i=0; i<27; i++) {
                    if(toupper(sInput2[j]) == sValid[i]) {
                        test = 1;
                        break;
                    }
            }
            if(test == 0) {
                ret = 0;
                break;
            }
        }
        return ret;
    }
    Basically, to start with:

    Replace string with C-style strings (null-terminated char arrays) and string operations with Standard C Library string functions.

    Move all the variable declarations to the top of the functions. That includes all those int declarations of i inside the for loops. This would not be necessary if you are targetting C99, but then you did not specify that.

    Replace cout with printf and cin with C-style input functions, such as scanf.

    Either create your own bool datatype with typedef or use int. A value of zero is false and a non-zero is true, so you could #define TRUE and FALSE as 1 and 0, respectively.
  4. #3
  5. Contributing User

    Join Date
    Aug 2003
    Location
    UK
    Posts
    5,117
    Rep Power
    1803
    Since your C++ code does not utilise C++'s OOP features (beyond using the std::string and iostream objects), the task is straightforward, but why bother? It is a backward step to a more primitive language. C++ compilers are as ubiquitous as C, in fact most C compilers are also C++ compilers.

    You'd do better perhaps to consider how your code might be improved. There are some remarkable inefficiencies. Rather than converting to upper case and scanning the alphabet you could simply call isalpha() - it is in the same header as toupper() (which in fact you have failed to include - cctype/ctype.h BTW). Even if you did not want to do that a simple range check:
    Code:
    bool alpha = (ch >= 'A' && ch <= 'Z') || (ch >= 'z' && ch <= 'z') ;
    is all that is required.
  6. #4
  7. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2013
    Posts
    9
    Rep Power
    0
    how do i create the bool datatype?
  8. #5
  9. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,255
    Rep Power
    2222
    Originally Posted by hmmshire
    how do i create the bool datatype?
    As I already said, use typedef. If you don't know how to use typedef, then now's the time to read up on it. Then you can define the true and false values as macros with #define.

    Give it a try. If you have problems, then show us what you did.

    PS
    Of course, there's the alternative of just replacing bool with the C way, which is using int. That's actually what defining bool with typedef would do; that way you eliminate the need to hunt down and change all code that used the bool.

    Stupid question that's already been raised: why the need to convert the code? Why can't you simply use a C++ compiler?
    Last edited by dwise1_aol; November 9th, 2013 at 11:17 PM.
  10. #6
  11. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2013
    Posts
    9
    Rep Power
    0
    infact i'm a student studying computer science and i'm a newbie concerning programming languages. i was given a question by my lecturer and was asked to write the program in C language. but as i only know c++ for the time being, i did it in c++. can you help me with the question? i'm having difficulties. and here it is :

    Develop an algorithm which takes an input sequence of characters from the
    alphabet {A,B,C} and compresses it by replacing each subsequence of a particular
    character by a single occurrence of the character, and the length of the substring.
    e.g. Input : AAAAABBBBBBBCCBBBAABBCCCCCS (27 x 8 bits = 216 bits)
    Output: A5B7C2B3A2B2C5 (14 x 8 bits = 112bits)

    Assuming that each character uses an 8-bit ASCII code your program should also
    calculate the percentage of compression:
    For example % compression = (Original size Compressed size) X 100
    Original size
    = (216-112)/216 X 100

    = 48.15 %

    You may use input file and output file if you know how to do it. (Tips: Make use of eof()
    function to detect the end of the input file.)
    (b) Using appropriate functions write a program to implement the above algorithm in C

    concerning the algorithm it's okay. i need help concerning the (b) part
  12. #7
  13. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2013
    Posts
    9
    Rep Power
    0

    infact i'm a student studying computer science and i'm a newbie concerning programmin


    infact i'm a student studying computer science and i'm a newbie concerning programming languages. i was given a question by my lecturer and was asked to write the program in C language. but as i only know c++ for the time being, i did it in c++. can you help me with the question? i'm having difficulties. and here it is :

    Develop an algorithm which takes an input sequence of characters from the
    alphabet {A,B,C} and compresses it by replacing each subsequence of a particular
    character by a single occurrence of the character, and the length of the substring.
    e.g. Input : AAAAABBBBBBBCCBBBAABBCCCCCS (27 x 8 bits = 216 bits)
    Output: A5B7C2B3A2B2C5 (14 x 8 bits = 112bits)

    Assuming that each character uses an 8-bit ASCII code your program should also
    calculate the percentage of compression:
    For example % compression = (Original size Compressed size) X 100
    Original size
    = (216-112)/216 X 100

    = 48.15 %

    You may use input file and output file if you know how to do it. (Tips: Make use of eof()
    function to detect the end of the input file.)
    (b) Using appropriate functions write a program to implement the above algorithm in C

    concerning the algorithm it's okay. i need help concerning the (b) part
  14. #8
  15. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,255
    Rep Power
    2222
    Originally Posted by hmmshire
    (b) Using appropriate functions write a program to implement the above algorithm in C

    concerning the algorithm it's okay. i need help concerning the (b) part
    clifford already pointed out that this is a very straightforward task. I already told you what changes you need to make:
    Originally Posted by dwise1_aol
    Basically, to start with:

    Replace string with C-style strings (null-terminated char arrays) and string operations with Standard C Library string functions.

    Move all the variable declarations to the top of the functions. That includes all those int declarations of i inside the for loops. This would not be necessary if you are targetting C99, but then you did not specify that.

    Replace cout with printf and cin with C-style input functions, such as scanf.

    Either create your own bool datatype with typedef or use int. A value of zero is false and a non-zero is true, so you could #define TRUE and FALSE as 1 and 0, respectively.
    Now, you do know about C-style strings, don't you? I've been in a great many programming classes. Except for a few exceptions, every single programming assignment depended on knowledge that we had already been taught. And the few exceptions to that all involved knowledge that we were about to be taught (and would be taught long before the assignment's due date) and that was readily available in the next chapter or section of our textbook. So I know that you have already been taught what you need to know for this part of the assignment.

    Of course, if you have not been doing your reading assignments or not attending class or not staying awake in class, then you wouldn't know what you need to know. But then whose fault would that be? And what other solution would there be but for you to catch up on your reading?

    OK, so maybe you might not have been taught about typedef yet, but that is very simple to look up in your textbook or via an on-line search.

    You need to replace the basic string class with C-style strings. You should already know what C-style strings are. You should already know that they are arrays of char and that you need to use the string functions on them, such as strcpy, strcat, strcmp, etc. You should already know that they are terminated by a null-terminator, a char whose ASCII code is zero. You should already know that you must always ensure that a new string is null-terminated (ie, if you write code that modifies a string directly, then you must take care of that null-terminated string yourself). And you should already know that you must not allow any array to overflow, so the char array that you declare to hold a string must be large enough to hold the longest string plus one more for the null-terminator.

    You should already know everything that you need to know to perform that translation. Do it! And as you have specific difficulties, then we can help you. But we will not do your homework for you, because then you wouldn't learn anything. We want you to learn.
    Last edited by dwise1_aol; November 10th, 2013 at 10:33 AM.
  16. #9
  17. Contributing User

    Join Date
    Aug 2003
    Location
    UK
    Posts
    5,117
    Rep Power
    1803
    Originally Posted by hmmshire
    how do i create the bool datatype?
    ISO C99 intoduced the type bool to C. If your compiler supports C99 (even partially), then all you need is:

    Code:
    #include <stdbool.h>
  18. #10
  19. Contributing User

    Join Date
    Aug 2003
    Location
    UK
    Posts
    5,117
    Rep Power
    1803
    Originally Posted by hmmshire
    ... was asked to write the program in C language. but as i only know c++ for the time being
    Your C++ code is very C-like - i..e not OO. C++ is more-or-less a superset of C++, all you need to do is use the subset that is valid C and there will be no problem. That is to say, if you know C++ you know C. Even the C standard library remains part of C++.

    My advice is to take your code, attempt to compile it as C and fix what breaks. Familiarise yourself with the C standard library (which is a subset of the C++ library documented here for example). For the post part, you will need to replace <iostream> usage with <stdio.h> calls, and std::string usage with C-style strings and the <string.h> library.
  20. #11
  21. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2013
    Posts
    9
    Rep Power
    0
    I'm trying to change the syntax but still it is not working. I'm compiling this in dev c++ program. it say string undeclared and whatsoever. Can you give it a try? And if it works please do post it here. I'll study and compare the codes with mine and determine where is the bug
  22. #12
  23. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2013
    Posts
    9
    Rep Power
    0
    Couldn't we just simply use 1 dimensional arrays instead of using c style stings? This will simplify just the codes making it less complex. In fact i'm not supposed to learn C language. I'm doing C++ only. This is just some additional work that my lecturer told we can do. He said it will be good if we know the C language as well. Self learning
  24. #13
  25. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,255
    Rep Power
    2222
    Originally Posted by hmmshire
    ... it say string undeclared and whatsoever.
    Yes, that's right. string is the basic string class now available in C++. C doesn't have classes. So as I already told you twice!:
    Originally Posted by dwise1_aol
    Replace string with C-style strings (null-terminated char arrays) and string operations with Standard C Library string functions.
    So that makes three times that I've had to tell you that. I trust that you do realize that I'm telling you that for a very good reason, which is that that is what you need to do!

    And I'll have you know that up until 1998 C++ used C-style strings. A lot of C++ books, especially pre-1998 and even afterwards, and on-line C++ programs use C-style strings.

    So convert all your strings to C-style strings. That part is really that simple.

    Originally Posted by hmmshire
    Couldn't we just simply use 1 dimensional arrays instead of using c style stings?
    C-style strings are one-dimensional arrays of char. And strings.h lists the functions that C provides for working with them.

    It's really quite simple. You could have learned it in less time than you've already wasted whining about it.
  26. #14
  27. Contributing User

    Join Date
    Aug 2003
    Location
    UK
    Posts
    5,117
    Rep Power
    1803
    Writing it in C++ (especially bad C++) then attempting to convert it to C was a really bad idea. You'd have done better to just learn C (the very tiny part of it you need to complete this).

    What kind of course are you on that requires you to program in a language that has not been taught? Was C a prerequisite? If it was, you chose teh wrong course, or should have done some pre-study. C is a very small language, you can learn it in a very short time. If you have C++, about a day just to figure out what C does not support.
  28. #15
  29. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,255
    Rep Power
    2222
    I performed the translation this morning and it took me about 20 minutes. If hmmshire had applied himself following our guidance, he should have been able to do the same after a couple hours or so, considering the very moderate learning curve he'd have encountered. Instead, he's dragged this on for nearly 3 and a half days with nothing so far to show for it.

    So, hmmshire, which is the more effective path? Applying yourself to the task? Or dawdling?
Page 1 of 2 12 Last
  • Jump to page:

IMN logo majestic logo threadwatch logo seochat tools logo