String in C

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • palm
    New Member
    • Feb 2007
    • 27

    String in C

    Hi Guyz,
    Does anyone know how to make a string (in C program) out of different types of variables? I have an int array called x and a string array called y. I need to make a string in the form of :

    y[0]x[0]y[1]x[1]..... (Eg: a1u3b2%3#8...)

    I tried to use strcat, but it's giving error saying my y array is int and it has to be char. Can some one help me plz... Does any one know how to create an array that can contain both int and string variables?


    Palm.
  • arne
    Recognized Expert Contributor
    • Oct 2006
    • 315

    #2
    Originally posted by palm
    Hi Guyz,
    Does anyone know how to make a string (in C program) out of different types of variables? I have an int array called x and a string array called y. I need to make a string in the form of :

    y[0]x[0]y[1]x[1]..... (Eg: a1u3b2%3#8...)

    I tried to use strcat, but it's giving error saying my y array is int and it has to be char. Can some one help me plz... Does any one know how to create an array that can contain both int and string variables?


    Palm.
    Does sprintf do want you want?

    Comment

    • palm
      New Member
      • Feb 2007
      • 27

      #3
      Hi Arne,
      Thanks for your quick response, but unfortunately sprintf doesn't seem working. It's saving my int value, but not the character "%". When I tried to save "%%", it's just saving blank space, not the % sign. This is what I tried:

      char *final="";
      sprintf(final," %%","%i", x[0]);

      if i just say sprintf(final," %i",x[0]), it saves what'z in my array x, but when i tried to save % sign, it's saving null, but it's working for other characters like # or @... How can I fix this problem?

      Palm.

      Comment

      • weaknessforcats
        Recognized Expert Expert
        • Mar 2007
        • 9214

        #4
        Do you mean like this:

        char str[10];
        char a[] = "%";
        char b[] = "#";
        char c[] = "@";
        char d[] = "";
        strcpy(str, d);
        strcat(str, a);
        strcat(str, b);
        strcat(str, c);
        strcat(str, d);
        cout << str << endl;

        ??

        Comment

        • palm
          New Member
          • Feb 2007
          • 27

          #5
          yes, i need to save first char to another array and first int to next element of that array then second char and then second int and so on....

          i tried to create a string with "%" sign following int and then "%" sign and then int using sprintf and strcat like this:

          while (x[i] != '\0'){
          sprintf (cha,"%s","%%") ;
          strcat (new,cha);
          sprintf (in,"%x",x[i]);
          strcat (new,in);
          }
          printf (cha);

          this is giving the following error:

          Memory fault(coredump)

          Does anyone know how to fix this problem?...


          Palm.

          Comment

          • palm
            New Member
            • Feb 2007
            • 27

            #6
            The code is working partially correct. I'm supposed to get this out put:

            %61%73%61%66%64 %28%61%64%66%61 %64%29%2f%5b%79 %65%73%20%3f%5d

            but I'm getting this out put:
            %61%735d5d

            which just prints first two % signs and the numbers properly and then last number twice for some reason. I'm totally confused... Could some one plz help me to get correct out put? This is my code:

            #include <stdio.h>
            #include <string.h>
            void main(){

            const char *test = "asafd(adfa d)/[yes ?]";
            char a[]="";
            char *t = strcpy(a,test);

            int y=0; int i=0;
            char *final=""; char *finall=""; char *what = "";

            while(a[y] != '\0')
            {
            i= a[y];
            final = strcat (finall, "%%");
            sprintf (what,"%x",i);
            finall = strcat (final,what);
            y++;
            }
            printf (finall);
            printf ("\n");
            }

            It's going inside while loop for 20 times (which is correct), but it's not saving those 20 characters and the % sign.

            Palm.

            Comment

            • palm
              New Member
              • Feb 2007
              • 27

              #7
              Does anyone have any clude?

              Palm.

              Comment

              • JosAH
                Recognized Expert MVP
                • Mar 2007
                • 11453

                #8
                Originally posted by palm
                Does anyone have any clude?

                Palm.
                I assume you know how to convert an int to a char* so your problem boils
                down to merging to strings together, a char from one, a char from the other etc.
                until one (or both) of the strings have been processed. You need another
                buffer for that, its length being equal to the sum of both the other char buffers.
                (plus one for the trailing \0' character).

                Let b1 and b2 be the two input buffers and out be the result buffer; the following
                can be a good start:
                Code:
                void merge(char* b1, char* b2, char* out) {
                
                   for (; *b1 && *b2; b1++, b2++) {
                      *(out++)= *b1;
                      *(out++)= *b2;
                   }
                // ...
                }
                You have to handle the (possible) postfixes of b1 and b2 yourself.

                kind regards,

                Jos

                Comment

                • palm
                  New Member
                  • Feb 2007
                  • 27

                  #9
                  Hi Jos,
                  Thanks for your help. I tried your method, but it's not giving proper out put though. It's working without any error and just saves % signs into out. Any other idea? Logic behind my while loop seems fine and it's going inside the loop 4 the correct number of time, but not saving all the characters in to my variable to out put....

                  Palm.

                  Comment

                  • weaknessforcats
                    Recognized Expert Expert
                    • Mar 2007
                    • 9214

                    #10
                    You have various memory corruption problems and you are always using strcat with the correct arrays AND printf is also not used correctly.

                    Here is your code that now works. No logic was changed. I just made comments and fixed the memory corruption problems.

                    Here is where you really need to learn how to use your debugger.


                    #include <stdio.h>
                    #include <string.h>
                    void main(){

                    const char *test = "asafd(adfa d)/[yes ?]";
                    //char a[]=""; //yours
                    char a[50] = ""; //mine
                    //
                    //WeaknessForCats :
                    //Memeory corruption here. the array "a" is one byte
                    // V
                    char *t = strcpy(a,test);

                    //int y=0; int i=0;
                    int y=0; char i=0;
                    //
                    //WeaknessForCats :
                    //Memory corruption here. These arrays are one byte each
                    //
                    //VVVVVVVVVVVVVVV VVVVVVVVVVVVVVV VVV
                    //char *final=""; char *finall=""; char *what = ""; //yours
                    char final[100]=""; char finall[100]=""; char what[100] = ""; //mine
                    while(a[y] != '\0')
                    {
                    i= a[y];
                    //
                    //WeaknessForCats
                    //Various errors here.
                    //final = strcat (finall, "%%"); //yours
                    strcat (finall, "%"); //mine
                    sprintf (what,"%x",i);
                    //finall = strcat (final,what); //yours
                    strcat(finall, what); //mine
                    y++;
                    }
                    //
                    //WeaknessForCats :
                    //printf always needs a parameter string as the first argument.
                    //printf (finall); //yours
                    // VVVV
                    printf("%s", finall); //mine
                    printf ("\n");
                    }

                    Comment

                    • palm
                      New Member
                      • Feb 2007
                      • 27

                      #11
                      Thanks a lot weaknessforcats ,
                      Thanks for pointing out my mistakes and explaining very clearly. I've corrected my code as you explained and it's working fine, except it's printing a garbage character infront of the string and deleted last 6 characters, but when i just put a printf statement before the initalization of arrays finall and what, it's printing fine. What's going on with this string?
                      #include <stdio.h>
                      #include <string.h>
                      void main(){
                      const char *test = "asafd(adfa d)/[yes ?]";
                      int size = strlen(test);
                      char a[size+1];
                      char *t = strcpy(a,test);
                      int y=0; char i=0;
                      printf ("");
                      char finall[size*2]; char what[size*2];
                      while(a[y] != '\0')
                      {
                      i= a[y];
                      strcat (finall, "%");
                      sprintf (what,"%x",i);
                      strcat(finall, what);
                      y++;
                      }
                      printf("%s", finall);
                      printf ("\n");
                      }

                      palm.

                      Comment

                      • weaknessforcats
                        Recognized Expert Expert
                        • Mar 2007
                        • 9214

                        #12
                        Most cases of oddball results are due to memory corruption. This case is no different. Your finall and what arrays were too small. Here is the corrected code compiled as straight C:

                        Code:
                         #include <stdio.h> 
                        #include <string.h> 
                        #include <stdlib.h>
                        void main(){
                        const char *test = "asafd(adfad)/[yes ?]";
                        int size = strlen(test);
                        //
                        //WeaknessForCats
                        //
                        //Array size needs to be known at compile time. size is not known until run
                        //time. In these situations, create the arrays on the heap.
                        //Some compilers support this feature but is not an ANSI feature.
                        //If you are using gcc, then you should use the -pedantic switch
                        //char a[size+1]; //yours
                        char* a = (char*)malloc(size + 1); //mine
                        char* finall = (char*)malloc((size*3) + 1); //mine - moved from below
                        char* what = (char*)malloc((size*3) + 1); //mine - moved from below
                        char *t = strcpy(a,test);
                        int y=0; char i=0;
                        printf (""); 
                        //
                        //WeaknessForCats
                        //These arrays are too small. They should be (size*3) + 1:
                        //char finall[size*2]; char what[size*2]; //yours
                        //Each character in test becomes %nn so you need 3 times the size and not 2.
                        //AND allow for a null terminator.
                        //Plus I had to move them to the top of the function since this is C and not C++.
                        //AND I had to initialize the arrays to null strings.
                        //VVVVVVVVVVVVVVVVVVVVVVVV
                        strcpy(finall, ""); //mine
                        strcpy(what, ""); //mine
                        while(a[y] != '\0') 
                        {
                        i= a[y]; 
                        strcat (finall, "%"); 
                        sprintf (what,"%x",i);
                        strcat(finall, what); 
                        y++;
                        }
                        printf("%s", finall); 
                        printf ("\n");
                        free(a); //mine
                        free(finall); //mine
                        free(what); //mine
                        }
                        This works using Visual Studio.NET 2005
                        Last edited by r035198x; Apr 16 '07, 01:49 PM. Reason: added code tags

                        Comment

                        • palm
                          New Member
                          • Feb 2007
                          • 27

                          #13
                          Hi weaknessforcats ,
                          Thankx a lot for you great help... It seems I didn't have most fundamental stffs in C.. thankz again for your hel.. It works perfect.

                          palm.

                          Comment

                          • r035198x
                            MVP
                            • Sep 2006
                            • 13225

                            #14
                            Let's all remember to use code tags when posting code.

                            Comment

                            • palm
                              New Member
                              • Feb 2007
                              • 27

                              #15
                              Yes sir/madam... I'll try my best to remember this note.

                              Palm.

                              Comment

                              Working...