Solved

assign a char arry to std::string in VC++ 7.0

Posted on 2003-10-23
15
1,419 Views
Last Modified: 2013-12-14
i was not able to assign any char array with more than 15 charactors into a std::string variable.  the variable will be corrupted.  it works fine with anything less or equal to 15 chars.  same code worked perfectly with VC++6.0.  why is this happening?  my program talks to an API, which expects its args as type of std::string, i have no control over that.  please help.

thanks!
hxia

0
Comment
Question by:hxia
  • 7
  • 5
  • 2
  • +1
15 Comments
 
LVL 8

Expert Comment

by:Exceter
ID: 9608314
Post yout code. Here's an example that should work fine,

#include <iostream>
#include <iomanip>
#include <string>

using namespace std;

int main()
{
    char arr[] = "My name is Exceter, well not really but it is my login name!!!";
    string s = arr;

    cout << s << endl;

    return 0;
}

Are you sure that the char array you are working with is null terminated?

Exceter
0
 
LVL 86

Expert Comment

by:jkr
ID: 9608323
Hmm, sounds strange - have you tried

char acLongArray [] = "kkropti89irokvlrotoitk,,,diieuhjmllwoooso88urjmmmmm!";

string str;

str.reserve ( strlen ( acLongArray));

str = acLongArray;

?
0
 
LVL 30

Accepted Solution

by:
Axter earned 150 total points
ID: 9608598
Please post your code.

The following should also work:

char acLongArray [] = "kkropti89irokvlrotoitk,,,diieuhjmllwoooso88urjmmmmm!";

string str(acLongArray, acLongArray + sizeof(acLongArray)-1);

or

string str(acLongArray, acLongArray + strlen(acLongArray));
0
 

Author Comment

by:hxia
ID: 9608613
nothing works at this point, i tried both above.  it is sth with VC++ 7.0.   this was originally 6.0 code, then my .net upgraded to vc++ 7.0  then this happened.
0
 
LVL 8

Expert Comment

by:Exceter
ID: 9608724
Post your code.
0
 

Author Comment

by:hxia
ID: 9608895

      string str;
      char a[100];

      _snprintf(a, 100, "andy testing sjusfna;sdlfjasl;fsd");
      str = a;

above code is just one of a many i tried.  i even started a new project to do this.  i am guessing my string libs are not running right on my machine, i just tried the same code on the other machine in VC++7.0 and it worked just fine.  what should i do at this point?
0
 
LVL 30

Expert Comment

by:Axter
ID: 9608979
What header files are you using?

Are you using the <string> header file or the <string.h> header file?

You should be using <string> header file.

You should try posting an entire example code.
0
Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

 
LVL 30

Expert Comment

by:Axter
ID: 9609029
I just ran the following code on VC++ 7.1, and it ran just fine:

#include <stdlib.h>
#include <string>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
      string str;
      char a[100];

      _snprintf(a, 100, "andy testing sjusfna;sdlfjasl;fsd");
      str = a;

      printf("%s\n", str.c_str());

      system("pause");
      return 0;
}


Please post an entire example code, like the above, so that we can see exactly what's failing, and how you're getting the failure results.
0
 
LVL 30

Expert Comment

by:Axter
ID: 9609043
Is your project a UNICODE project or ANSI?
0
 

Author Comment

by:hxia
ID: 9609138
// andy.cpp : Defines the entry point for the application.
//

#include "stdafx.h"
#include "andy.h"
#include <stdlib.h>
#include <string>
#include <stdio.h>
#define MAX_LOADSTRING 100

using namespace std;

// Global Variables:
HINSTANCE hInst;                                                // current instance
TCHAR szTitle[MAX_LOADSTRING];                              // The title bar text
TCHAR szWindowClass[MAX_LOADSTRING];                  // the main window class name

// Forward declarations of functions included in this code module:
ATOM                        MyRegisterClass(HINSTANCE hInstance);
BOOL                        InitInstance(HINSTANCE, int);
LRESULT CALLBACK      WndProc(HWND, UINT, WPARAM, LPARAM);
LRESULT CALLBACK      About(HWND, UINT, WPARAM, LPARAM);

int APIENTRY _tWinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPTSTR    lpCmdLine,
                     int       nCmdShow)
{

      string str;
      char a[100];

      _snprintf(a, 100, "andy testing sjusfna;sdlfjasl;fsd");
      str = a;

       // TODO: Place code here.
      MSG msg;
      HACCEL hAccelTable;

      // Initialize global strings
      LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
      LoadString(hInstance, IDC_ANDY, szWindowClass, MAX_LOADSTRING);
      MyRegisterClass(hInstance);

      // Perform application initialization:
      if (!InitInstance (hInstance, nCmdShow))
      {
            return FALSE;
      }

      hAccelTable = LoadAccelerators(hInstance, (LPCTSTR)IDC_ANDY);

      // Main message loop:
      while (GetMessage(&msg, NULL, 0, 0))
      {
            if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
            {
                  TranslateMessage(&msg);
                  DispatchMessage(&msg);
            }
      }

      return (int) msg.wParam;
}

The same code runs on other machines.  But on mine, it complies, runs and gets junks from the assignment.  This test code is win32.
0
 
LVL 30

Expert Comment

by:Axter
ID: 9609298
How do you know it's failing?
The above code does not ouput the contents of str, so there's no way to tell if it fails.

Try modifiying it to the following:
      string str;
      char a[100];

      _snprintf(a, 100, "andy testing sjusfna;sdlfjasl;fsd");
      str = a;

      MessageBox(NULL,str.c_str(), "", 0);

When I run this on 7.1, I get a messagebox with the full contents.
0
 

Author Comment

by:hxia
ID: 9609583
i ran it in debuggar, and watched the values.  the string variable is corrupted after assignment.
0
 
LVL 30

Expert Comment

by:Axter
ID: 9610461
>>i ran it in debuggar, and watched the values.  the string variable is corrupted after assignment.

Sometimes the debugger can display misleading information.  Try displaying it via MessageBox or on the screen to verify it's contents.

MessageBox(NULL,str.c_str(), "", 0);


That will tell you for sure if it's currupt.
0
 

Author Comment

by:hxia
ID: 9614010
ok, i tried to display.  only junks in it.  again, in the debugger, the str had a valid pointer and correct contents, but stringbuf is currupted and had those junks in there somehow.    none of this is happened on other machines when i tried.  at this point i will try to upgrade my .net to 2003, use VC++7.1 instead, hopefully, i will work right this time.  all the answers are correct i am sure, thank you all.
0
 
LVL 30

Expert Comment

by:Axter
ID: 9614029
>> i will try to upgrade my .net to 2003, use VC++7.1 instead

7.1 is much better then 7.0, so it's well worth the effort and the cost for the upgrade.

The 7.1 version is more C++ compliant then the 3.x GNU compiler.
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Article by: SunnyDark
This article's goal is to present you with an easy to use XML wrapper for C++ and also present some interesting techniques that you might use with MS C++. The reason I built this class is to ease the pain of using XML files with C++, since there is…
This article shows you how to optimize memory allocations in C++ using placement new. Applicable especially to usecases dealing with creation of large number of objects. A brief on problem: Lets take example problem for simplicity: - I have a G…
The viewer will learn how to synchronize PHP projects with a remote server in NetBeans IDE 8.0 for Windows.
The viewer will learn how to use and create new code templates in NetBeans IDE 8.0 for Windows.

746 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now