"AlexD_UK" <al*********@hotmail.com> wrote in message
news:e3**************************@posting.google.c om...
When I try the first option with new Class Library (.NET) project and
the following code :
// TestC5.h
#pragma once
#include <string>
using namespace System;
namespace TestC5
{
public __gc class Class1
{
};
void method(void)
{
char str1[]= "To be or not to be";
char str2[6];
strncpy (str2,str1,5);
}
}
I get this error :
TestC++5 error LNK2020: unresolved token (0A000006) _CxxThrowException
TestC++5 error LNK2020: unresolved token (0A000017) delete
strncpy is part of the <cstring> header of the std namespace, not System
namespace which is part of the .net <mscorlib.dll>. Also, you need to make
sure you allocate enough n characters in strncpy(str2, str1, n) or it will
truncate. n needs to allocate enough room for the string plus the null
character at the end.
Just using standard c++, here's how I would rewrite and compile the code:
#include <cstring>
#include <iostream>
using namespace std;
int main()
{
const char str1[] = "To be or not to be";
char str2[24];
strncpy(str2,str1,23);
cout << str1 << endl;
cout << str2 << endl;
}
I do though, get this warning when compiling with VS.NET 8.0 beta:
cstrcpy.cpp(9) : warning C4996: 'strncpy' was declared deprecated
D:\Program Files\Microsoft Visual Studio 8\VC\include\string.h(121)
: see declaration of 'strncpy'
Microsoft (R) Incremental Linker Version 8.00.40607.16
Copyright (C) Microsoft Corporation. All rights reserved.
It is unsafe and cumbersome to use C style chars. Better to use safer
standard C++ strings:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str1 = "To be or not to be";
string str2 = str1;
cout << str1 << endl;
cout << str2 << endl;
}
str1 can be as long or short as you want, and you don't have to worry about
allocating enough when copying it to str2.
- Don Kim