junni lomo
junni lomo

Reputation: 779

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;
}

Upvotes: 2

Views: 8101

Answers (3)

masoud
masoud

Reputation: 56549

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.

Upvotes: 3

hmjd
hmjd

Reputation: 122011

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).

Upvotes: 8

zmbq
zmbq

Reputation: 39079

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.

Upvotes: 2

Related Questions