Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
CODE PROJECT For Those Who Code
  • Home
  • Articles
  • FAQ
Community
  1. Home
  2. General Programming
  3. C / C++ / MFC
  4. Simple C to C++ [modified]

Simple C to C++ [modified]

Scheduled Pinned Locked Moved C / C++ / MFC
c++debuggingquestion
28 Posts 9 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • S Offline
    S Offline
    Software2007
    wrote on last edited by
    #1

    Hi, I would like to convert this function from C to C++.I attempted the conversion below, but not sure if I got it correctly. - note: debugger would crash at msg[i] = nul in the c-like code. -I also have the feeling this function can be written in 2 lines with strings! Thanks

    #define NUL 0
    char z_buf[4095]

    void replace_html_delimiters(char *msg)
    {
    for(i=0; ; i++)
    {
    if(msg[i]== NUL)
    break;
    if(msg[i]=='<')
    {
    msg[i] = NUL;
    strcpy(z_buf,msg);
    strcat(z_buf,"<");
    strcat(z_buf,msg+i+1);//confusing me
    strcpy(msg,z_buf);
    }
    }
    }

    //C++

    <pre lang="c++">
    #define NUL 0
    char z_buf[4095]

    void replace_html_delimiters(string msg)
    {
    for(i=0; ; i++) //Why no upper limit here?
    {
    if(msg[i]== NUL)
    break;
    if(msg[i]=='<')
    {
    msg[i] = NUL;
    strcpy(z_buf,msg.c_str());
    z_buf += "<";
    strcat(z_buf,msg.rightOf[i]);
    strcpy(msg,z_buf);
    }
    }
    }</pre>

    modified on Wednesday, September 14, 2011 2:30 PM

    L C enhzflepE O S 8 Replies Last reply
    0
    • S Software2007

      Hi, I would like to convert this function from C to C++.I attempted the conversion below, but not sure if I got it correctly. - note: debugger would crash at msg[i] = nul in the c-like code. -I also have the feeling this function can be written in 2 lines with strings! Thanks

      #define NUL 0
      char z_buf[4095]

      void replace_html_delimiters(char *msg)
      {
      for(i=0; ; i++)
      {
      if(msg[i]== NUL)
      break;
      if(msg[i]=='<')
      {
      msg[i] = NUL;
      strcpy(z_buf,msg);
      strcat(z_buf,"<");
      strcat(z_buf,msg+i+1);//confusing me
      strcpy(msg,z_buf);
      }
      }
      }

      //C++

      <pre lang="c++">
      #define NUL 0
      char z_buf[4095]

      void replace_html_delimiters(string msg)
      {
      for(i=0; ; i++) //Why no upper limit here?
      {
      if(msg[i]== NUL)
      break;
      if(msg[i]=='<')
      {
      msg[i] = NUL;
      strcpy(z_buf,msg.c_str());
      z_buf += "<";
      strcat(z_buf,msg.rightOf[i]);
      strcpy(msg,z_buf);
      }
      }
      }</pre>

      modified on Wednesday, September 14, 2011 2:30 PM

      L Offline
      L Offline
      Lost User
      wrote on last edited by
      #2

      You could do it like this:

      string replace_html_delimiters(string msg)
      {
      for(int i=0;msg[i];i++)
      if(msg[i] == '<')
      msg.replace(i,1,"<",0,4); // "& l t ;", CodeProject won't display this properly but I'm guessing this is what you want.

      return msg;
      

      }

      The msg[i] == NUL has been moved to the for-loop and the replace[^] function is used for replacing '<'-characters with & l t ;. Note that unlike with a char array, a string will not be modified when passed to a function like this. I solved this by returning the output string, but you could also convert your function to accept a string pointer as argument.

      S 1 Reply Last reply
      0
      • L Lost User

        You could do it like this:

        string replace_html_delimiters(string msg)
        {
        for(int i=0;msg[i];i++)
        if(msg[i] == '<')
        msg.replace(i,1,"<",0,4); // "& l t ;", CodeProject won't display this properly but I'm guessing this is what you want.

        return msg;
        

        }

        The msg[i] == NUL has been moved to the for-loop and the replace[^] function is used for replacing '<'-characters with & l t ;. Note that unlike with a char array, a string will not be modified when passed to a function like this. I solved this by returning the output string, but you could also convert your function to accept a string pointer as argument.

        S Offline
        S Offline
        Software2007
        wrote on last edited by
        #3

        Great, I think this is what I needed. I ma not sure about the for(int i=0;msg[i];i++) as a terminating condition. Did you mean to put something else instead of msg[i]?

        C C 2 Replies Last reply
        0
        • S Software2007

          Great, I think this is what I needed. I ma not sure about the for(int i=0;msg[i];i++) as a terminating condition. Did you mean to put something else instead of msg[i]?

          C Offline
          C Offline
          Chris Losinger
          wrote on last edited by
          #4

          when msg[i] = 0, the loop will stop. ('false' = 0, in C/C++)

          image processing toolkits | batch image processing

          S 1 Reply Last reply
          0
          • C Chris Losinger

            when msg[i] = 0, the loop will stop. ('false' = 0, in C/C++)

            image processing toolkits | batch image processing

            S Offline
            S Offline
            Software2007
            wrote on last edited by
            #5

            for(int i=0;msg[i]=0;i++) crashes. for(int i=0;msg[i] !=' ';i++) seems to be okay.

            C 1 Reply Last reply
            0
            • S Software2007

              for(int i=0;msg[i]=0;i++) crashes. for(int i=0;msg[i] !=' ';i++) seems to be okay.

              C Offline
              C Offline
              Chris Losinger
              wrote on last edited by
              #6

              Software2007 wrote:

              for(int i=0;msg[i]=0;i++) crashes.

              msg[i]=0 is an assignment. (sorry, i wasn't speaking C, when i typed it, in my comment above) 'msg[i]' in a conditional is equivalent to 'msg[i]!=0'

              image processing toolkits | batch image processing

              S 1 Reply Last reply
              0
              • C Chris Losinger

                Software2007 wrote:

                for(int i=0;msg[i]=0;i++) crashes.

                msg[i]=0 is an assignment. (sorry, i wasn't speaking C, when i typed it, in my comment above) 'msg[i]' in a conditional is equivalent to 'msg[i]!=0'

                image processing toolkits | batch image processing

                S Offline
                S Offline
                Software2007
                wrote on last edited by
                #7

                Sorry, but I am a bit confused. I am on C++ compiler now, and both of the following crash. for(int i=0;msg[i]=0;i++) //I understand this is no good, it's an assignment for(int i=0;msg[i]!=0;i++)//but shouldn't this work? "Expression string out of range"

                C 1 Reply Last reply
                0
                • S Software2007

                  Sorry, but I am a bit confused. I am on C++ compiler now, and both of the following crash. for(int i=0;msg[i]=0;i++) //I understand this is no good, it's an assignment for(int i=0;msg[i]!=0;i++)//but shouldn't this work? "Expression string out of range"

                  C Offline
                  C Offline
                  Chris Losinger
                  wrote on last edited by
                  #8

                  Software2007 wrote:

                  but shouldn't this work?

                  yes, it should. what's the value of i when it crashes ? and how long is the string?

                  image processing toolkits | batch image processing

                  S 1 Reply Last reply
                  0
                  • C Chris Losinger

                    Software2007 wrote:

                    but shouldn't this work?

                    yes, it should. what's the value of i when it crashes ? and how long is the string?

                    image processing toolkits | batch image processing

                    S Offline
                    S Offline
                    Software2007
                    wrote on last edited by
                    #9

                    I send in a string "Test"; 19 characters long. The loop crashes at index 25 for(int i=0;msg[i];i++) { if(msg[i] == '<') msg.replace(i,1,"<",0,4); } The string actually becomes 25 characters after replacing '<' with //"<", so the very last iteration, it increments i to 25, it tries to check the condition msg[25], I believe it crashes since the string is only 24 chars long ?

                    modified on Wednesday, September 14, 2011 4:09 PM

                    D C C 3 Replies Last reply
                    0
                    • S Software2007

                      I send in a string "Test"; 19 characters long. The loop crashes at index 25 for(int i=0;msg[i];i++) { if(msg[i] == '<') msg.replace(i,1,"<",0,4); } The string actually becomes 25 characters after replacing '<' with //"<", so the very last iteration, it increments i to 25, it tries to check the condition msg[25], I believe it crashes since the string is only 24 chars long ?

                      modified on Wednesday, September 14, 2011 4:09 PM

                      D Offline
                      D Offline
                      David Crow
                      wrote on last edited by
                      #10

                      Software2007 wrote:

                      The loop crashes at index 25

                      How are you calling replace_html_delimiters()?

                      Software2007 wrote:

                      msg.replace(i,1,"<",0,4);

                      Crashing aside, why are you replacing < with the string equivalent? Wouldn't a simple msg[i] = '<'; suffice?

                      "One man's wage rise is another man's price increase." - Harold Wilson

                      "Fireproof doesn't mean the fire will never come. It means when the fire comes that you will be able to withstand it." - Michael Simmons

                      "Some people are making such thorough preparation for rainy days that they aren't enjoying today's sunshine." - William Feather

                      S 1 Reply Last reply
                      0
                      • D David Crow

                        Software2007 wrote:

                        The loop crashes at index 25

                        How are you calling replace_html_delimiters()?

                        Software2007 wrote:

                        msg.replace(i,1,"<",0,4);

                        Crashing aside, why are you replacing < with the string equivalent? Wouldn't a simple msg[i] = '<'; suffice?

                        "One man's wage rise is another man's price increase." - Harold Wilson

                        "Fireproof doesn't mean the fire will never come. It means when the fire comes that you will be able to withstand it." - Michael Simmons

                        "Some people are making such thorough preparation for rainy days that they aren't enjoying today's sunshine." - William Feather

                        S Offline
                        S Offline
                        Software2007
                        wrote on last edited by
                        #11

                        I am trying to replace the C code in my original post. Unfortuantely, CodeProject keeps replacing my "& l t ;" with "<". I had to put spaces just now to display it, but in the code, there is no space between the 4 letters.

                        1 Reply Last reply
                        0
                        • S Software2007

                          I send in a string "Test"; 19 characters long. The loop crashes at index 25 for(int i=0;msg[i];i++) { if(msg[i] == '<') msg.replace(i,1,"<",0,4); } The string actually becomes 25 characters after replacing '<' with //"<", so the very last iteration, it increments i to 25, it tries to check the condition msg[25], I believe it crashes since the string is only 24 chars long ?

                          modified on Wednesday, September 14, 2011 4:09 PM

                          C Offline
                          C Offline
                          Chris Losinger
                          wrote on last edited by
                          #12

                          this works for me:

                          #include <string>

                          void repl(std::string &msg)
                          {
                          for(int i=0;msg[i];i++)
                          {
                          if(msg[i] == '<')
                          msg.replace(i,1,"<",0,4);
                          }
                          }

                          int _tmain(int argc, _TCHAR* argv[])
                          {
                          std::string f = "<title>blah</title>";

                          repl(f);

                          return 0;
                          

                          }

                          image processing toolkits | batch image processing

                          S 1 Reply Last reply
                          0
                          • C Chris Losinger

                            this works for me:

                            #include <string>

                            void repl(std::string &msg)
                            {
                            for(int i=0;msg[i];i++)
                            {
                            if(msg[i] == '<')
                            msg.replace(i,1,"<",0,4);
                            }
                            }

                            int _tmain(int argc, _TCHAR* argv[])
                            {
                            std::string f = "<title>blah</title>";

                            repl(f);

                            return 0;
                            

                            }

                            image processing toolkits | batch image processing

                            S Offline
                            S Offline
                            Software2007
                            wrote on last edited by
                            #13

                            The same code you showed me crashes at index 25! I am running just simple console app in VS2010. It works on VS2008! Oh well! Thanks for your help

                            modified on Wednesday, September 14, 2011 4:31 PM

                            C 1 Reply Last reply
                            0
                            • S Software2007

                              The same code you showed me crashes at index 25! I am running just simple console app in VS2010. It works on VS2008! Oh well! Thanks for your help

                              modified on Wednesday, September 14, 2011 4:31 PM

                              C Offline
                              C Offline
                              Chris Losinger
                              wrote on last edited by
                              #14

                              how about a generic std::string find/replace fn:

                              void repl2(std::string &str, const char *find, const char *repl)
                              {
                              // should probably quit if either of these are 0!
                              size_t findLen = strlen(find);
                              size_t replLen = strlen(repl);

                              size_t index = 0;
                              while (true) {
                              /* Locate the substring to replace. */
                              index = str.find(find, index);
                              if (index == std::string::npos) break;

                                /\* Make the replacement. \*/
                                str.replace(index, findLen, repl);
                              
                                /\* Advance index forward so the next iteration doesn't pick it up as well. \*/
                                index+=replLen;
                              

                              }
                              }

                              that's based on something from this thread[^].

                              image processing toolkits | batch image processing

                              1 Reply Last reply
                              0
                              • S Software2007

                                Hi, I would like to convert this function from C to C++.I attempted the conversion below, but not sure if I got it correctly. - note: debugger would crash at msg[i] = nul in the c-like code. -I also have the feeling this function can be written in 2 lines with strings! Thanks

                                #define NUL 0
                                char z_buf[4095]

                                void replace_html_delimiters(char *msg)
                                {
                                for(i=0; ; i++)
                                {
                                if(msg[i]== NUL)
                                break;
                                if(msg[i]=='<')
                                {
                                msg[i] = NUL;
                                strcpy(z_buf,msg);
                                strcat(z_buf,"<");
                                strcat(z_buf,msg+i+1);//confusing me
                                strcpy(msg,z_buf);
                                }
                                }
                                }

                                //C++

                                <pre lang="c++">
                                #define NUL 0
                                char z_buf[4095]

                                void replace_html_delimiters(string msg)
                                {
                                for(i=0; ; i++) //Why no upper limit here?
                                {
                                if(msg[i]== NUL)
                                break;
                                if(msg[i]=='<')
                                {
                                msg[i] = NUL;
                                strcpy(z_buf,msg.c_str());
                                z_buf += "<";
                                strcat(z_buf,msg.rightOf[i]);
                                strcpy(msg,z_buf);
                                }
                                }
                                }</pre>

                                modified on Wednesday, September 14, 2011 2:30 PM

                                C Offline
                                C Offline
                                Chuck OToole
                                wrote on last edited by
                                #15

                                Well, I'm not even sure the straight C code works. 'msg' is a 'char *', meaning it points to a string of characters owned by the caller of the function. Presumably that string is in some buffer allocated by the caller. When you complete the replace using the temporary 'z_buf' buffer (presumably large enough, but assume it is), you them move the new (possibly longer) string back into the buffer pointed to by 'msg'. How do you know you aren't overwriting that buffer? How do you know it's large enough to receive the replaced string? I'm just saying, you could be clobbering something important.

                                1 Reply Last reply
                                0
                                • S Software2007

                                  Great, I think this is what I needed. I ma not sure about the for(int i=0;msg[i];i++) as a terminating condition. Did you mean to put something else instead of msg[i]?

                                  C Offline
                                  C Offline
                                  Chuck OToole
                                  wrote on last edited by
                                  #16

                                  for (int i=0; msg[i]; i++) is equivalent to: for (int i=0; msg[i]!=0; i++) The end condition is the character at msg[i] being the null at the end of the string. The compiler didn't like msg[i]=0 because that's an assignment, not an equality test. Need another '=' in there.

                                  1 Reply Last reply
                                  0
                                  • S Software2007

                                    Hi, I would like to convert this function from C to C++.I attempted the conversion below, but not sure if I got it correctly. - note: debugger would crash at msg[i] = nul in the c-like code. -I also have the feeling this function can be written in 2 lines with strings! Thanks

                                    #define NUL 0
                                    char z_buf[4095]

                                    void replace_html_delimiters(char *msg)
                                    {
                                    for(i=0; ; i++)
                                    {
                                    if(msg[i]== NUL)
                                    break;
                                    if(msg[i]=='<')
                                    {
                                    msg[i] = NUL;
                                    strcpy(z_buf,msg);
                                    strcat(z_buf,"<");
                                    strcat(z_buf,msg+i+1);//confusing me
                                    strcpy(msg,z_buf);
                                    }
                                    }
                                    }

                                    //C++

                                    <pre lang="c++">
                                    #define NUL 0
                                    char z_buf[4095]

                                    void replace_html_delimiters(string msg)
                                    {
                                    for(i=0; ; i++) //Why no upper limit here?
                                    {
                                    if(msg[i]== NUL)
                                    break;
                                    if(msg[i]=='<')
                                    {
                                    msg[i] = NUL;
                                    strcpy(z_buf,msg.c_str());
                                    z_buf += "<";
                                    strcat(z_buf,msg.rightOf[i]);
                                    strcpy(msg,z_buf);
                                    }
                                    }
                                    }</pre>

                                    modified on Wednesday, September 14, 2011 2:30 PM

                                    C Offline
                                    C Offline
                                    Chuck OToole
                                    wrote on last edited by
                                    #17

                                    In the C++ example, just what does

                                    strcpy(msg,z_buf);

                                    do to the string object? Assuming it compiles, are you clobbering the object? I don't use the std:: classes much, but if this were MFC/ATL CString, the strcpy argument would use a typecasting to get a pointer to the internal buffer of CString (char *) which you are *NEVER ALLOWED TO OVERWRITE*. Yet the strcpy() call does exactly that. I would imagine that std::string has a similar internal structure and would be very upset if you started overwriting its content.

                                    1 Reply Last reply
                                    0
                                    • S Software2007

                                      I send in a string "Test"; 19 characters long. The loop crashes at index 25 for(int i=0;msg[i];i++) { if(msg[i] == '<') msg.replace(i,1,"<",0,4); } The string actually becomes 25 characters after replacing '<' with //"<", so the very last iteration, it increments i to 25, it tries to check the condition msg[25], I believe it crashes since the string is only 24 chars long ?

                                      modified on Wednesday, September 14, 2011 4:09 PM

                                      C Offline
                                      C Offline
                                      Chuck OToole
                                      wrote on last edited by
                                      #18

                                      It is my understanding that std::string does *NOT* include a NULL ('\0') character at the end of the string. One cannot assume a null termination. So, basically you are using C style assumptions on C++ string objects. The way to deal with std::string is through the member functions string.length(), string.replace(), etc. The examples others have shown you work because they stay within the object's definition of operative functions. There is a string.c_str() member function that returns a pointer to a C style null terminated char * (http://www.cplusplus.com/reference/string/string/c_str/[^]) but that too cannot be modified by the receiving program. If you're going to convert from C to C++, you should go all the way and avoid those old char * uses and move to some string class, either std::string or MFC/ATL CString, depending on your project's needs.

                                      1 Reply Last reply
                                      0
                                      • S Software2007

                                        Hi, I would like to convert this function from C to C++.I attempted the conversion below, but not sure if I got it correctly. - note: debugger would crash at msg[i] = nul in the c-like code. -I also have the feeling this function can be written in 2 lines with strings! Thanks

                                        #define NUL 0
                                        char z_buf[4095]

                                        void replace_html_delimiters(char *msg)
                                        {
                                        for(i=0; ; i++)
                                        {
                                        if(msg[i]== NUL)
                                        break;
                                        if(msg[i]=='<')
                                        {
                                        msg[i] = NUL;
                                        strcpy(z_buf,msg);
                                        strcat(z_buf,"<");
                                        strcat(z_buf,msg+i+1);//confusing me
                                        strcpy(msg,z_buf);
                                        }
                                        }
                                        }

                                        //C++

                                        <pre lang="c++">
                                        #define NUL 0
                                        char z_buf[4095]

                                        void replace_html_delimiters(string msg)
                                        {
                                        for(i=0; ; i++) //Why no upper limit here?
                                        {
                                        if(msg[i]== NUL)
                                        break;
                                        if(msg[i]=='<')
                                        {
                                        msg[i] = NUL;
                                        strcpy(z_buf,msg.c_str());
                                        z_buf += "<";
                                        strcat(z_buf,msg.rightOf[i]);
                                        strcpy(msg,z_buf);
                                        }
                                        }
                                        }</pre>

                                        modified on Wednesday, September 14, 2011 2:30 PM

                                        enhzflepE Offline
                                        enhzflepE Offline
                                        enhzflep
                                        wrote on last edited by
                                        #19

                                        The reason there's no upper limit on "i" in either of the for loops is that this would take more code - it would require a strlen be performed once before the loop in addition to checking to see if i is equal to this length. It's less clear to read and more prone to induce error during maintenance, but I believe it to be for this reason that the way the loop is exited with a break. Not sure why you'd go the trouble of #defining NUL as 0x0.. It would be clearer if the already provided NULL was used (less code too, since there's only 4 references to 'NUL' - 4 cases of simply adding another 'L'. In any case, the executable code is identical - it is just the source-code that suffers from reduced readability, unlike the loop-terminating-condition check, which produces a smaller executable when done this way than the more readable alternative of checking the strlen first then using a terminarting condition of ichar *htmlStr = ""; replace_html_delimiters(htmlStr); while I can see this succeeding

                                        char *htmlStr = "";
                                        char htmlStrCopy = strdup(htmlStr);
                                        replace_html_delimiters(htmlStrCopy);
                                        ..
                                        .. other actions on htmlStrCopy
                                        ..
                                        free(htmlStrCopy);

                                        Add to that the fact that the "char z_buf[4095]" statement isn't terminated with a ';' in either case and you have rather a problem, considering that the C function called with a string containing "" returns the same string. Studying the function, it appears to scan through a string, quitting upon end of string (0x0), while perplexingly, when it intercepts a '<' character it copies all of the text except for this character, then it appends the '<' explicitly. It's 5am here, and I can't think of a circumstance that the output sring would be different to the input string.

                                        C 1 Reply Last reply
                                        0
                                        • enhzflepE enhzflep

                                          The reason there's no upper limit on "i" in either of the for loops is that this would take more code - it would require a strlen be performed once before the loop in addition to checking to see if i is equal to this length. It's less clear to read and more prone to induce error during maintenance, but I believe it to be for this reason that the way the loop is exited with a break. Not sure why you'd go the trouble of #defining NUL as 0x0.. It would be clearer if the already provided NULL was used (less code too, since there's only 4 references to 'NUL' - 4 cases of simply adding another 'L'. In any case, the executable code is identical - it is just the source-code that suffers from reduced readability, unlike the loop-terminating-condition check, which produces a smaller executable when done this way than the more readable alternative of checking the strlen first then using a terminarting condition of ichar *htmlStr = ""; replace_html_delimiters(htmlStr); while I can see this succeeding

                                          char *htmlStr = "";
                                          char htmlStrCopy = strdup(htmlStr);
                                          replace_html_delimiters(htmlStrCopy);
                                          ..
                                          .. other actions on htmlStrCopy
                                          ..
                                          free(htmlStrCopy);

                                          Add to that the fact that the "char z_buf[4095]" statement isn't terminated with a ';' in either case and you have rather a problem, considering that the C function called with a string containing "" returns the same string. Studying the function, it appears to scan through a string, quitting upon end of string (0x0), while perplexingly, when it intercepts a '<' character it copies all of the text except for this character, then it appends the '<' explicitly. It's 5am here, and I can't think of a circumstance that the output sring would be different to the input string.

                                          C Offline
                                          C Offline
                                          Chuck OToole
                                          wrote on last edited by
                                          #20

                                          You're right in that the code looks odd but I think it was because the Code Project Editor messed it up. The OP was trying to replace the < character with the sequence ampersand-l-t, a sequence which if typed into this editor will yield a <, making the code look wrong. He's really making the string bigger with the replacements.

                                          1 Reply Last reply
                                          0
                                          Reply
                                          • Reply as topic
                                          Log in to reply
                                          • Oldest to Newest
                                          • Newest to Oldest
                                          • Most Votes


                                          • Login

                                          • Don't have an account? Register

                                          • Login or register to search.
                                          • First post
                                            Last post
                                          0
                                          • Categories
                                          • Recent
                                          • Tags
                                          • Popular
                                          • World
                                          • Users
                                          • Groups