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
  1. Home
  2. General Programming
  3. C / C++ / MFC
  4. How to convert a CString object to char array in VC++ MFC

How to convert a CString object to char array in VC++ MFC

Scheduled Pinned Locked Moved C / C++ / MFC
c++data-structurestutorialquestion
13 Posts 6 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.
  • U User 4396598

    Hi, Is there any MFC method to convert CString object to char array? please tell me how to do this. Thanks in advance. Regards, jo

    hi

    J Offline
    J Offline
    Joe Woodbury
    wrote on last edited by
    #3

    CString s(_T("Hello World"));
    TCHAR* pStr = new TCHAR[s.GetLength() + 1];
    lstrcpy(pStr, s);
    _putts(pStr);
    delete [] pStr;

    U 1 Reply Last reply
    0
    • J Joe Woodbury

      CString s(_T("Hello World"));
      TCHAR* pStr = new TCHAR[s.GetLength() + 1];
      lstrcpy(pStr, s);
      _putts(pStr);
      delete [] pStr;

      U Offline
      U Offline
      User 4396598
      wrote on last edited by
      #4

      Thanks joe :) i have one more problem. please check the code below here pdmFile,pdmSecFile are two CFile objs.

      CString strLine;
      totlen = pdmFile.GetLength();
      for(int i = 0; i < totlen; i++)
      {
      	UINT lBytesRead = pdmFile.Read(ch,1);
      	if(ch\[0\] == '\\n')
      	{
      		int totl = strLine.GetLength();
      
      		TCHAR\* pStr = new TCHAR\[strLine.GetLength() + 1\];
      		lstrcpy(pStr, strLine);
      
      		pdmSecFile.Write(pStr, totl+1);
      		delete \[\] pStr;
      		pdmSecFile.Flush();
      		strLine.ReleaseBuffer(); 
      		strLine.Empty();
      	}
      	strLine.AppendChar(ch\[0\]);
      }
      pdmFile.Close();
      pdmSecFile.Close();
      

      iam trying to read each line from the first file and writing to second file. i am getting the out put but after every character its printing NULL character. please check the code and give me some solution to get the desired output. Thanks in advance! Regards, jo

      hi

      J 1 Reply Last reply
      0
      • A Adam Roderick J

        It is not at all good to convert a CString to char array unless you are sure that it doesn't contain any UNICODE character. well there a lot of methods one of them is CString csdata = "asdsadasdda"; char* cdata = csdata.GetBuffer(); //When you have done all your needs, use ReleaseBuffer(). csdata.ReleaseBuffer();

        Величие не Бога может быть недооценена.

        modified on Monday, January 25, 2010 1:36 AM

        C Offline
        C Offline
        Cedric Moonen
        wrote on last edited by
        #5

        Adam Roderick J 09 wrote:

        char* cdata = csdata.GetBuffer();

        Calling GetBuffer is not a good solution in this case, even if you call ReleaseBuffer afterward. There's no need to use GetBuffer because CString already defines casting operators (which returns the same type of what GetBuffer returns, so it depends on the UNICODE settings). Using GetBuffer is very bad practice and should be avoided.

        Cédric Moonen Software developer
        Charting control [v3.0] OpenGL game tutorial in C++

        A 1 Reply Last reply
        0
        • U User 4396598

          Thanks joe :) i have one more problem. please check the code below here pdmFile,pdmSecFile are two CFile objs.

          CString strLine;
          totlen = pdmFile.GetLength();
          for(int i = 0; i < totlen; i++)
          {
          	UINT lBytesRead = pdmFile.Read(ch,1);
          	if(ch\[0\] == '\\n')
          	{
          		int totl = strLine.GetLength();
          
          		TCHAR\* pStr = new TCHAR\[strLine.GetLength() + 1\];
          		lstrcpy(pStr, strLine);
          
          		pdmSecFile.Write(pStr, totl+1);
          		delete \[\] pStr;
          		pdmSecFile.Flush();
          		strLine.ReleaseBuffer(); 
          		strLine.Empty();
          	}
          	strLine.AppendChar(ch\[0\]);
          }
          pdmFile.Close();
          pdmSecFile.Close();
          

          iam trying to read each line from the first file and writing to second file. i am getting the out put but after every character its printing NULL character. please check the code and give me some solution to get the desired output. Thanks in advance! Regards, jo

          hi

          J Offline
          J Offline
          Joe Woodbury
          wrote on last edited by
          #6

          First, there is no need to do the copy operation. pdmSecFile.Write((LPCTSTR) pStr, strLine.GetLength() * sizeof(TCHAR)); is sufficient (which also elminates the int totl = line.) Second, you are writing out the NULL character with totl+1. Third, the Flush is not needed. Fourth, ReleaseBuffer is not needed. Fifth, you should append the char immediately, and then test. Otherwise the last return never gets written. Sixth, the last line may never get written if it doesn't end in a return. Seventh, just use CStdioFile and have it read the entire string for you!

          U 1 Reply Last reply
          0
          • C Cedric Moonen

            Adam Roderick J 09 wrote:

            char* cdata = csdata.GetBuffer();

            Calling GetBuffer is not a good solution in this case, even if you call ReleaseBuffer afterward. There's no need to use GetBuffer because CString already defines casting operators (which returns the same type of what GetBuffer returns, so it depends on the UNICODE settings). Using GetBuffer is very bad practice and should be avoided.

            Cédric Moonen Software developer
            Charting control [v3.0] OpenGL game tutorial in C++

            A Offline
            A Offline
            Adam Roderick J
            wrote on last edited by
            #7

            thanks for correcting me. :-D

            Величие не Бога может быть недооценена.

            1 Reply Last reply
            0
            • J Joe Woodbury

              First, there is no need to do the copy operation. pdmSecFile.Write((LPCTSTR) pStr, strLine.GetLength() * sizeof(TCHAR)); is sufficient (which also elminates the int totl = line.) Second, you are writing out the NULL character with totl+1. Third, the Flush is not needed. Fourth, ReleaseBuffer is not needed. Fifth, you should append the char immediately, and then test. Otherwise the last return never gets written. Sixth, the last line may never get written if it doesn't end in a return. Seventh, just use CStdioFile and have it read the entire string for you!

              U Offline
              U Offline
              User 4396598
              wrote on last edited by
              #8

              Thanks joe for your comments. i changed code like this to eliminate char array.

              CFile pdmFile;
              CFile pdmSecFile;
              
              pdmFile.Open(\_T("c:\\\\strucadv15\\\\Work\\\\testpdms\\\\mod\\\\testpdms.pdm"),CFile::modeRead);
              pdmSecFile.Open(\_T("c:\\\\strucadv15\\\\Work\\\\testpdms\\\\mod\\\\testpdms\_changed.pdm"),CFile::modeCreate | CFile::modeReadWrite);
              
              
              CString strLinee;
              totlen = pdmFile.GetLength();
              for(int i = 0; i < totlen; i++)
              {
              	UINT lBytesRead = pdmFile.Read(ch,1);
              	if(ch\[0\] == '\\n')
              	{
              		pdmSecFile.Write(strLinee, strLinee.GetLength());
              		strLinee.Empty();
              	}
              	strLinee.AppendChar(ch\[0\]);
              }
              pdmFile.Close();
              pdmSecFile.Close();
              

              but still i got the same output like, after every character its appending one NULL please give me some solution. :) Regards, Jo

              hi

              M J 2 Replies Last reply
              0
              • U User 4396598

                Thanks joe for your comments. i changed code like this to eliminate char array.

                CFile pdmFile;
                CFile pdmSecFile;
                
                pdmFile.Open(\_T("c:\\\\strucadv15\\\\Work\\\\testpdms\\\\mod\\\\testpdms.pdm"),CFile::modeRead);
                pdmSecFile.Open(\_T("c:\\\\strucadv15\\\\Work\\\\testpdms\\\\mod\\\\testpdms\_changed.pdm"),CFile::modeCreate | CFile::modeReadWrite);
                
                
                CString strLinee;
                totlen = pdmFile.GetLength();
                for(int i = 0; i < totlen; i++)
                {
                	UINT lBytesRead = pdmFile.Read(ch,1);
                	if(ch\[0\] == '\\n')
                	{
                		pdmSecFile.Write(strLinee, strLinee.GetLength());
                		strLinee.Empty();
                	}
                	strLinee.AppendChar(ch\[0\]);
                }
                pdmFile.Close();
                pdmSecFile.Close();
                

                but still i got the same output like, after every character its appending one NULL please give me some solution. :) Regards, Jo

                hi

                M Offline
                M Offline
                Maya_
                wrote on last edited by
                #9

                totlen = pdmFile.GetLength(); <- This gives you no of chars in the file. So for loop iterates for each char and you are inserting null char: -> strLinee.AppendChar(ch[0]); You should look for a new line char to get the no of lines in the file.

                U J 2 Replies Last reply
                0
                • M Maya_

                  totlen = pdmFile.GetLength(); <- This gives you no of chars in the file. So for loop iterates for each char and you are inserting null char: -> strLinee.AppendChar(ch[0]); You should look for a new line char to get the no of lines in the file.

                  U Offline
                  U Offline
                  User 4396598
                  wrote on last edited by
                  #10

                  Thanks Maya! :) what you said is correct... but i solved that problem in different way, I guess this is the easiest way. any how I am keeping that code here, it will be helpful for others. I used CStdioFile instead of CFile, that really simplifies my work.

                  CStdioFile pdmFile;
                  CStdioFile pdmSecFile;
                  
                  pdmFile.Open(m\_sPdmFileName, CStdioFile::modeRead);
                  pdmSecFile.Open(\_T("testpdms\_changed.pdm"),CStdioFile::modeCreate | CStdioFile::modeReadWrite);
                  
                  CString sKey;
                  CString sValue;
                  POSITION pos;
                  while(pdmFile.ReadString(strLine))
                  {
                  	pos =  mapingStrings.GetStartPosition();
                  	while(pos != NULL)
                  	{
                  		mapingStrings.GetNextAssoc(pos, sKey, sValue);
                  		strLine.Replace(sKey,sValue);
                  	}
                  	pdmSecFile.WriteString(strLine);
                  	pdmSecFile.WriteString(\_T("\\n"));
                  }
                  pdmFile.Close();
                  pdmSecFile.Close();
                  

                  Regards, Jo

                  hi

                  1 Reply Last reply
                  0
                  • U User 4396598

                    Hi, Is there any MFC method to convert CString object to char array? please tell me how to do this. Thanks in advance. Regards, jo

                    hi

                    M Offline
                    M Offline
                    Madan Chauhan
                    wrote on last edited by
                    #11

                    hi .. Use _tcscpy() to copy from CString to TCHAR array; ex- CString csMystring = L"Hi all"; TCHAR tchChar[MAX_PATH]; memset(tchChar, 0x00, MAX_PATH); _tcscpy(tchChar, csMystring); Hope it will help. Thanks MChauhan

                    1 Reply Last reply
                    0
                    • U User 4396598

                      Thanks joe for your comments. i changed code like this to eliminate char array.

                      CFile pdmFile;
                      CFile pdmSecFile;
                      
                      pdmFile.Open(\_T("c:\\\\strucadv15\\\\Work\\\\testpdms\\\\mod\\\\testpdms.pdm"),CFile::modeRead);
                      pdmSecFile.Open(\_T("c:\\\\strucadv15\\\\Work\\\\testpdms\\\\mod\\\\testpdms\_changed.pdm"),CFile::modeCreate | CFile::modeReadWrite);
                      
                      
                      CString strLinee;
                      totlen = pdmFile.GetLength();
                      for(int i = 0; i < totlen; i++)
                      {
                      	UINT lBytesRead = pdmFile.Read(ch,1);
                      	if(ch\[0\] == '\\n')
                      	{
                      		pdmSecFile.Write(strLinee, strLinee.GetLength());
                      		strLinee.Empty();
                      	}
                      	strLinee.AppendChar(ch\[0\]);
                      }
                      pdmFile.Close();
                      pdmSecFile.Close();
                      

                      but still i got the same output like, after every character its appending one NULL please give me some solution. :) Regards, Jo

                      hi

                      J Offline
                      J Offline
                      Joe Woodbury
                      wrote on last edited by
                      #12

                      Member 4399771 wrote:

                      after every character its appending one NULL

                      You are writing a UNICODE string to the file. Each AppendChar() converts the character to a UNICODE character and appends it to the string. During your write, you'll also note that only half the string is being written. (CString::GetLength() returns the number of characters, not the number of bytes.)

                      1 Reply Last reply
                      0
                      • M Maya_

                        totlen = pdmFile.GetLength(); <- This gives you no of chars in the file. So for loop iterates for each char and you are inserting null char: -> strLinee.AppendChar(ch[0]); You should look for a new line char to get the no of lines in the file.

                        J Offline
                        J Offline
                        Joe Woodbury
                        wrote on last edited by
                        #13

                        That's not correct. He reads a character at a time and then appends it. The problem is that the concatenation operation is likely creating a UNICODE string.

                        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