how do I clear a string?

Started by
13 comments, last by PPCThug 20 years, 1 month ago
Oh, I finally understand what you were trying to do in the original post. In this line:

char szPrime01[12] = {" "};

Those braces are used to specify what each of the 12 characters should be initialized to. You only entered one character, a space, which set the first character to a space but all the others are still random garbage, and that''s why they appear as blocks. If you try using " " (multiple spaces) instead, that''s not a valid character, that''s a string, so you got an error. The correct way to initialize the string is like this:

char szPrime01[12] = {0};

0 is the null-terminator and that sets the first character to it, which means the string is equal to "". Anyway, to explain more about the syntax, to initialize the string to "ABC" you''d do this:

char szPrime01[12] = {''A'', ''B'', ''C'', 0};


~CGameProgrammer( );

Screenshots of your games or desktop captures -- Post screenshots of your projects. There''s already 134 screenshot posts.
~CGameProgrammer( );Developer Image Exchange -- New Features: Upload screenshots of your games (size is unlimited) and upload the game itself (up to 10MB). Free. No registration needed.
Advertisement
actually I had several spaces, either I didn''t type them in to the first post or they got removed by the board. initializing the strings with {" "} several spaces got rid of several invalid charecters but not the first and last ones.

char szPrime01 [12] = {"\0"}; compiled, ran, still get invalid charecters

char szPrime01 [12] = {"0"}; compiled, ran, still get invalid charecters

char szPrime01 [12] = {0}; compiled, ran, still get invalid charecters

char szPrime01 [12] = 0; invalid initializer

heres the entire program

#include <windows.h>#include <string>#include <stdio.h>HWND         hwnd ;int iLength;char szPrime01 [12] = {"\0"};char szPrime02 [12] = {"\0"};char szPrime03 [12] = {"\0"};char szPrime04 [12] = {"\0"};char szPrime05 [12] = {"\0"};unsigned long int realnum = 3, divisor = 2;unsigned short int count = 0; //, fuse = 0;char quit;bool OnOff = true;// char *psPrime = TEXT ("Found Prime number:"); a pointer to a text string// text out worked with a constant string but not the pointerLRESULT CALLBACK WndProc (HWND, UINT, WPARAM, LPARAM) ;void PrimeGenerator ();int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance,                    PSTR szCmdLine, int iCmdShow){     static TCHAR szAppName[] = TEXT ("PrimeFinderWin01") ;     MSG          msg ;     WNDCLASS     wndclass ;     wndclass.style         = CS_HREDRAW | CS_VREDRAW ;     wndclass.lpfnWndProc   = WndProc ;     wndclass.cbClsExtra    = 0 ;     wndclass.cbWndExtra    = 0 ;     wndclass.hInstance     = hInstance ;     wndclass.hIcon         = LoadIcon (NULL, IDI_APPLICATION) ;     wndclass.hCursor       = LoadCursor (NULL, IDC_ARROW) ;     wndclass.hbrBackground = (HBRUSH) GetStockObject (WHITE_BRUSH) ;     wndclass.lpszMenuName  = NULL ;     wndclass.lpszClassName = szAppName ;     if (!RegisterClass (&wndclass))     {          MessageBox (NULL, TEXT ("This program requires Windows NT!"),                       szAppName, MB_ICONERROR) ;          return 0 ;     }          hwnd = CreateWindow (szAppName,                            // window class name                          TEXT ("Prime Finder windows 01"),     // window caption                          WS_OVERLAPPEDWINDOW,                  // window style                          CW_USEDEFAULT,                        // initial x position                          CW_USEDEFAULT,                        // initial y position                          CW_USEDEFAULT,                        // initial x size                          CW_USEDEFAULT,                        // initial y size                          NULL,                                 // parent window handle                          NULL,                                 // window menu handle                          hInstance,                            // program instance handle                          NULL) ;                               // creation parameters          ShowWindow (hwnd, iCmdShow) ;     UpdateWindow (hwnd) ;          while ( true)        {             if (PeekMessage (&msg, NULL, 0, 0, PM_REMOVE))           {          if (msg.message == WM_QUIT)             break;                  TranslateMessage (&msg) ;             DispatchMessage (&msg) ;                        }                     if (OnOff == true)           PrimeGenerator ();                           }     return msg.wParam ;}LRESULT CALLBACK WndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam){     static int  cxChar, cxCaps, cyChar ;     HDC         hdc ;     PAINTSTRUCT ps ;     RECT        rect ;     TCHAR       szBuffer [10] ;     TEXTMETRIC  tm ;          switch (message)     {     case WM_CREATE:          // PlaySound (TEXT ("hellowin.wav"), NULL, SND_FILENAME | SND_ASYNC) ;          // a relic of the original program                    hdc = GetDC (hwnd) ;          GetTextMetrics (hdc, &tm) ;          cxChar = tm.tmAveCharWidth ;          cxCaps = (tm.tmPitchAndFamily & 1 ? 3 : 2) * cxChar / 2 ;          cyChar = tm.tmHeight + tm.tmExternalLeading ;          ReleaseDC (hwnd, hdc) ;                    return 0 ;               case WM_PAINT:          hdc = BeginPaint (hwnd, &ps) ;                    GetClientRect (hwnd, &rect) ;                    TextOut (hdc, 0, cyChar * 0, TEXT ("Found Prime number:"), 19) ;          TextOut (hdc, 0, cyChar * 1, TEXT ("Found Prime number:"), 19) ;          TextOut (hdc, 0, cyChar * 2, TEXT ("Found Prime number:"), 19) ;          TextOut (hdc, 0, cyChar * 3, TEXT ("Found Prime number:"), 19) ;          TextOut (hdc, 0, cyChar * 4, TEXT ("Found Prime number:"), 19) ;                    TextOut (hdc, cxChar * 20, cyChar * 0, szPrime01, 12) ;          TextOut (hdc, cxChar * 20, cyChar * 1, szPrime02, 12) ;          TextOut (hdc, cxChar * 20, cyChar * 2, szPrime03, 12) ;          TextOut (hdc, cxChar * 20, cyChar * 3, szPrime04, 12) ;          TextOut (hdc, cxChar * 20, cyChar * 4, szPrime05, 12) ;                    //DrawText (hdc, TEXT ("Will I even be using this text function?!"), -1, &rect,          //          DT_SINGLELINE | DT_LEFT | DT_TOP) ;                    EndPaint (hwnd, &ps) ;                    Sleep (100);                    return 0 ;               case WM_DESTROY:          PostQuitMessage (0) ;          return 0 ;     }     return DefWindowProc (hwnd, message, wParam, lParam) ;}void PrimeGenerator (){if (divisor >= realnum)   {                            // std::cout << "Prime number: " << realnum << "\n";  doesn''t work in win32   /* cannot copy strings or arrays!!!   szPrime01 = szPrime02;   szPrime02 = szPrime03;   szPrime03 = szPrime04;   szPrime04 = szPrime05;   */      strcpy ( szPrime01, szPrime02);   strcpy ( szPrime02, szPrime03);   strcpy ( szPrime03, szPrime04);   strcpy ( szPrime04, szPrime05);      sprintf ( szPrime05, TEXT (" %u  "), realnum);      // szPrime05 = realnum; can''t convert from unsigned int to char string      InvalidateRect (hwnd, NULL, TRUE);                                                                                                                      realnum += 2;   divisor = 2;   count++;      if (count >= 15)      {              OnOff = false;                                         // std::cout << "Do you want to quit?(y to quit)\n"; doesn''t work in win32       // std::cin >> quit; same here              /*                    all work and no play yada yada yada       if ( quit == ''y'' )                 break;          else                 count = 0;        */                  }                   }      if ((realnum % divisor) != 0)      {      divisor++;      }         else      {         realnum += 2;      divisor = 2;                  /*                        for some reasion this         if (fuse = 60000)         counter quit the program          {                         before it should have!?          break;          }        */      }            }



Bloodshed Dev-C++ 4.9.8.0
DX 9.0a DX SDK 6.1
win98
#define WIN32_LEAN_AND_MEAN
the Particle Projection Cannon fires a shimmering blue bolt, much like a cross between lightning and a sine wave that ripples along its path.
Bloodshed Dev-C++ 4.9.8.0 Mingw DX 9.0a DX SDK 6.1win2k#define WIN32_LEAN_AND_MEANthe Particle Projection Cannon fires a shimmering blue bolt, much like a cross between lightning and a sine wave that ripples along its path.mechwarrior 2 mercenaries, 4 particle projection cannons, thug chassis
you have included STRING and hence you are using C++... why not use std::strings instead of char*?

std::string mystring("const char* constructor");

mystring contains the words "const char* constructor".

to clear the string (or set it to contain something else)...

mystring.assign("");

mystring is now empty.... and then...

mystring.assign("New text");

it now contains the words "New text". Then if you need to use it with a function that is expecting a const char*... you just go:

mystring.c_str();

(that's the C string). The reason you are having problems with your program BTW is that textout wants to know how many characters are in your string... the terminating '\0' has nothing to do with it. I would recomment you either use strlen (or whatever it's called) to get the string length, and feed that as the length parameter (ie not 12!!!)... or (preferably) switch to STL std::string...
in which case... the length parameter becomes mystring.size().

EDIT: forgot about board eating pointy brackets. Also, if you need sprintf type functions.. then you can use string streams instead of just strings.. in which case "mystringstream.str().c_str()" is the character content... and "mystringstream.str().size()" is the length, and you can clear it with mystringstream.str("")... but most importantly.. you can feed text/numbers to it like std::cout.

[edited by - dmounty on February 21, 2004 6:00:08 PM]
Still not sure what you're trying to do, but here's the low-down. When you're declaring a string as an array of characters and you use bracket notation, the string is terminated for you.

char string1[12] = {'\0'};
or
char string1[12] = {0};

is the same as
char string1[12] = "";
or even
char string1[12] = {'A', 'B'};

They're all null terminated, but the last two are terminated implicitly. You can check that with strlen().

When assigning a new string to an old char array, you use strcpy(), but first you have to make sure that the array is large enough. Use strlen to find out how big the array being copied is, then use malloc to make your other array big enough. For this purpose, use char*.

For example, declare string1 like this:
char *string1 = " ";
It's null terminated automatically, if you were wondering.
then:
string1 = (char*)malloc(sizeof(string2));
and finally:
strcpy(string1, string2);

So anyway, your problem is that in TextOut() you're saying the length of your string is 12, when in reality it's not. It's the size up to the null-terminator. So instead of 12, use strlen(szPrime0x).


Tolerance is a drug. Sycophancy is a disease.

[edited by - fisheyel83l on February 21, 2004 6:17:48 PM]
Tolerance is a drug. Sycophancy is a disease.
TextOut (hdc, cxChar * 20, cyChar * 0, szPrime01, strlen(szPrime01)) ;          TextOut (hdc, cxChar * 20, cyChar * 1, szPrime02, strlen(szPrime02)) ;          TextOut (hdc, cxChar * 20, cyChar * 2, szPrime03, strlen(szPrime03)) ;          TextOut (hdc, cxChar * 20, cyChar * 3, szPrime04, strlen(szPrime04)) ;          TextOut (hdc, cxChar * 20, cyChar * 4, szPrime05, strlen(szPrime05)) ;


fixed it

thought it needed the lenght of the array, not the number of char's contained therin

... I should refresh the page more often...

[edited by - ppcthug on February 21, 2004 6:35:01 PM]
Bloodshed Dev-C++ 4.9.8.0 Mingw DX 9.0a DX SDK 6.1win2k#define WIN32_LEAN_AND_MEANthe Particle Projection Cannon fires a shimmering blue bolt, much like a cross between lightning and a sine wave that ripples along its path.mechwarrior 2 mercenaries, 4 particle projection cannons, thug chassis

This topic is closed to new replies.

Advertisement