Solved

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

Posted on 2003-10-23
15
1,423 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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

  Included as part of the C++ Standard Template Library (STL) is a collection of generic containers. Each of these containers serves a different purpose and has different pros and cons. It is often difficult to decide which container to use and …
Container Orchestration platforms empower organizations to scale their apps at an exceptional rate. This is the reason numerous innovation-driven companies are moving apps to an appropriated datacenter wide platform that empowers them to scale at a …
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…

920 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

15 Experts available now in Live!

Get 1:1 Help Now