string to array of chars

I have a program that reads and writes inventory info to a .dat file.
The main routine uses strings, but in the class they are to be converted into
an array of chars. The program works fine except when I enter a string with a space. I get -8698759 garbage.
Here is my get and set methods.

void Tool::set_name(string name)
{
const char* strname = name.c_str();
strncpy_s(m_name, 25, strname, 25);

}

string Tool::get_name() const
{
return m_name;
}

Thanks in advance.

josea
Hi josea321!
It seems that you missused the strncpy function.That function only has 3 parameters, you wrote:
 
strncpy_s(m_name, 25, strname, 25);

And the function is strncpy, not strncpy_s. The strncpy_s function seems to be some kind of microsoft function, maybe your compiler doesn't even have it. You should stick to the standard library of C++, otherwise your code won't be cross platform.Here' s how the strncpy function looks:
 
strncpy (str2, str1, n);

Here's a code that i made, but i made the variables 'name' and 'm_name' global, because i didn't have access to the memebers of your class:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include<iostream>
#include<cstring>

using namespace std;

string name="Apple"; // the global variables, data members in your class 
char m_name[]="Orange";

void set_name() // i've removed the name parameter because in my case it's a global variable
{
  const char* strname = name.c_str();
  strncpy(m_name,strname, 25);
}

string get_name()
{
  return m_name;
}

int main()
{
    cout<<name<<endl; // writes the value of 'name'

    set_name(); // sets the value of 'm_name' which is "Orange" to the value of 'name'

    cout<<get_name()<<endl; // the value of m_name should be "Apple" now
    cout<<m_name; // just to be shore it's "Apple"

    return 0;
}

Basically they are the same functions, just that the're not in a class
The output of that code is:

Apple
Apple
Apple

which shows that the copy takes place.
Remember: try to use as much as you can function from the standard library, not from microsoft or other non cross-platform and non open-source libraries
Last edited on
Topic archived. No new replies allowed.