简体   繁体   中英

strcpy_s in c++

I am new to C++ . I am writing following simple code. I wanted to pass the character[40] into a function and then get the same as output. If i put a debug at following point. strcpy_s(x,100,tester);

But it only takes "This" if i write "This is sent at the output". Can anyone please point out what am i missing and whats the reason for only accepting few characters.

// BUSTesting.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include "resource.h"

int testFunction(char* tester);
int _tmain()
{

    char m[40];
    std::cin>>m;
    testFunction(m);
}
int testFunction(char* tester)
{

    char x[100] ;
    memset(x,100,sizeof(x));
    strcpy_s(x,100,tester);
    std::cout<<x;
    return 0;
}

operator>> will stop consuming input at first whitespace character. An alternative would be to use cin.getline() to prevent processing of input due to whitespace.

Note to initialize an array and avoid memset() :

char x[100] = "";

Recommend std::string and std::getline() which avoids specifying a maximum number of characters to read from the input stream (avoiding potential buffer overrun problems with fixed sized arrays).

Change this: std::cin >> m; to this cin.getline(m, 39);

cin >> x doesn't get all line characters until end-line when there is a white-space (space, tab, ...) in the input.

Since you are using C++, it is better to use std::string class instead of old C-style strings.

std::cin>>m probably breaks the string on a space for some reason. Break with a debugger and check m 's content. If it's only this , you've found the problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM