CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 16
  1. #1
    Join Date
    May 2005
    Location
    Estonia
    Posts
    235

    [RESOLVED] Adding char to beginning of string

    I have variable that is sometimes like 2 digits, but sometimes it goes to 1 digit, like 0, 1, 2 etc.
    And when it's < 2 then i need to add zero (char) before it so it will look like 01, 02 etc.
    I know strcat can merge strings but it can add strings(chars) only at the end of char. but i need to add to the beginning of string or char.
    Im using Borland C++ 3.1. There is strnset and i can add char with this to beginning but it erases number that i have (1, 2, 3 etc) (almost useless function).
    I made same app in Pascal, there was so easy:
    Code:
    if length(var1) < 2 then var1:='0' + var1
    but C++ don't accept this, so all i need to know how to do this '0' + var1 in C++.
    If somebody knows how to solve this then plz let me know. Im searching in Google also.
    Any hints or tips are welcome.

    thx in advance.
    Last edited by BytePtr; July 4th, 2005 at 05:20 PM.

  2. #2
    Join Date
    Apr 2005
    Location
    Norway
    Posts
    3,934

    Re: Adding char to beginning of string

    Like this?
    Code:
    const char pcszUnfixed[] = "5";
    char* pszFixed;
    
    if (strlen(pcszUnfixed) < 2)
    {
        // prefix string with '0'
        pszFixed = new char[strlen(pcszUnfixed) + 2];
        strcpy(pszFixed, "0");
        strcat(pszFixed, pcszUnfixed);
    } else
    {
        // just make a copy of the original string
        pszFixed = strdup(pcszUnfixed);
    }
    
    // print string
    printf("%s --> %s\n", pcszUnfixed, pszFixed);
    
    // clean up
    delete[] pszFixed;
    - petter

  3. #3
    Join Date
    Jun 2005
    Posts
    1,255

    Re: Adding char to beginning of string

    Another way to do it is:

    Code:
    char var1[3];
    if (strlen(var1) < 2) {
       strcpy(&var1[1], &var[0]);
       var1[0] = '0';
    }
    I don't use "new", because I presume that your variable is declared with a length of at least three characters, otherwise it wouldn't be able to contain 2-digit-numbers.

  4. #4
    Join Date
    May 2004
    Location
    Norway
    Posts
    655

    Re: Adding char to beginning of string

    Quote Originally Posted by BytePtr
    I made same app in Pascal, there was so easy:
    Code:
    if length(var1) < 2 then var1:='0' + var1
    but C++ don't accept this, so all i need to know how to do this '0' + var1 in C++.
    This is just as easy in C++.
    Code:
    #include <string>
    ...
    std::string var1("4");
    
    if(var1.length() < 2)
        {
        var1 = '0' + var1;
        }
    Insert entertaining phrase here

  5. #5
    Join Date
    Oct 2000
    Location
    London, England
    Posts
    4,773

    Re: Adding char to beginning of string

    Pretty sure it can be done with streams. Set the width to 2 and the padding to '0'?

    Anyway, that is assuming we start with something other than a string. But if we already startr with a string then:
    Code:
    if (s.size() < 2 )
    {
       s.insert(0, '0' );
    }

  6. #6
    Join Date
    May 2005
    Location
    Estonia
    Posts
    235

    Re: Adding char to beginning of string

    Thanks alot for all, i will try this all out and post results.

  7. #7
    Join Date
    May 2004
    Location
    Michigan, United States
    Posts
    457

    Re: Adding char to beginning of string

    If you're just using character arrays, sprintf can make things easy:
    Code:
    char szResult[3];   // two digits plus null
    sprintf(szResult, "%02s", szNumber);
    This will always return a two-character string with a leading zero, if needed, so you don't need to test for length < 2 (unless you want to).
    Programming today is a race between software engineers striving to build bigger and better idiot-proof programs and the Universe trying to produce bigger and better idiots. So far, the Universe is winning.

  8. #8
    Join Date
    May 2005
    Location
    Estonia
    Posts
    235

    Re: Adding char to beginning of string

    Bond it can be make simpler but i need later this variable in graphics mode. Output will be made with: outtext().
    And sprintf cannot output text in graphics mode.
    Thx anyway. I will write this hint down for future.

  9. #9
    Join Date
    Jun 2002
    Posts
    1,417

    Re: Adding char to beginning of string

    Quote Originally Posted by Bond
    This will always return a two-character string with a leading zero, if needed, so you don't need to test for length < 2 (unless you want to).
    That's not correct. the 2 in %02s is only the MINUMUM number of characters, not the maximum or exact number. if szNumber is your example is "1234", then the result of that sprintf will be "1234". Example:
    Code:
    int main() 
    { 
    	char szNumber[] = "1234";
    	char buf[8];
    	sprintf(buf,"%02s",szNumber);
    	printf("%s\n",buf);
    	return 0;
    }

  10. #10
    Join Date
    Apr 2004
    Location
    Canada
    Posts
    1,342

    Re: Adding char to beginning of string

    There is a very simple solution:

    Code:
    #include <iostream>
    #include <iomanip>
    
    int number;  // can be 1 or 2 digits
    cout << setw(2) << number;   // will output a preceding zero if it's one digit
    If you need to store the number in a string, you can use an ostringstream object instead of cout.
    Old Unix programmers never die, they just mv to /dev/null

  11. #11
    Join Date
    Jun 2002
    Posts
    1,417

    Re: Adding char to beginning of string

    Quote Originally Posted by BytePtr
    Bond it can be make simpler but i need later this variable in graphics mode. Output will be made with: outtext().
    And sprintf cannot output text in graphics mode.
    Thx anyway. I will write this hint down for future.
    The text has to be formatted somehow before you can send it to any GUI function for diplay. sprintf() is just doing that formatting, and you have to call other functions to display the string.

  12. #12
    Join Date
    May 2004
    Location
    Michigan, United States
    Posts
    457

    Re: Adding char to beginning of string

    Quote Originally Posted by stober
    That's not correct. the 2 in %02s is only the MINUMUM number of characters, not the maximum or exact number. if szNumber is your example is "1234", then the result of that sprintf will be "1234".
    You are correct. Based on his original question where he states it will be "sometimes 2, but also sometimes 1" and the fact that he only wants to pad the number to fill a two-character field, I was assuming that the number would always be one or two digits. I may have misunderstood.

    Thanks.
    Programming today is a race between software engineers striving to build bigger and better idiot-proof programs and the Universe trying to produce bigger and better idiots. So far, the Universe is winning.

  13. #13
    Join Date
    May 2005
    Location
    Estonia
    Posts
    235

    Re: Adding char to beginning of string

    Only working solution that i have worked out is to display zero as char or string if length of variable is less than 2 else display as usually.
    I got it working with strcat but i must work out normal program flow so it will call strcat only when length < 2. i guess i must make some function or procedure. it works now but im getting overflow and windows diplays errors. Yeah it's clock stuff.
    Code:
    #include <conio.h>
    #include <dos.h>
    #include <string.h>
    #include <stdlib.h>
    #include <iostream.h>
    
    int main(void)
    
    {
    	clrscr();
    
    	struct time t;
    
    	int sekund;
    	char *sek;
    	char *null="0";
    
    	while(!kbhit())
    	{
    	gettime(&t);
    	sekund = t.ti_sec;
    	itoa(sekund, sek, 10);
    
    	if(strlen(sek) < 2)
    	{
    		strcat(null, sek);
    		gotoxy(3,3);
    		delay(1000);
    		clrscr();
    		cprintf(null);
    	}
    	else
    	{
    		gotoxy(3,3);
    		delay(1000);
    		clrscr();
    		cprintf(sek);
    	}
    	}
    
    
    	getch();
    	return 0;
    }
    Problem is that program calls strcat every second if length < 2 b(thats why overwflows) but i need to call it only once if length < 2 and display zero until its needed. Thats why i must work out right program flow. maybe using some goto's. but it's bad.
    Last edited by BytePtr; July 8th, 2005 at 12:00 PM.

  14. #14
    Join Date
    Jun 2002
    Posts
    1,417

    Re: Adding char to beginning of string

    re-read post #7, Bond already showed you an easy way to do it. Its not necessary to check for string length.

  15. #15
    Join Date
    Jun 2005
    Posts
    94

    Re: Adding char to beginning of string

    edit** check my next post
    Last edited by thre3dee; July 9th, 2005 at 09:37 PM.

Page 1 of 2 12 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured