1

I am new to C++ and I have started to work with strings recently, but I have problems with strcpy_s(). In Visual Studio if I use the old strcpy() it said that it is unsafe and after reading more on the internet and I found out why so I started to use no more the strcpy(). In strcpy(), I have to tell it the size of buffer, but with this I have problems,because if I use strlen() it said that the buffer it is too small, even if I put a=strlen(string)+1,so I found out about another one called size_t(),and now I have no more problems with the error related to the buffer, but I got another error.

Error Link

Code:

#include <iostream>
#include <cstring>
#include <conio.h>
using namespace std;
int main()
{
    int  i, size_of_word;
    char word[202];
    cin.get(word, 201, '\n');
    cin.get();
    i = 0;
    while (i < strlen(word) - 1)
    {
        if (word[i] == word[i + 1])
        { 
            size_of_word = size_t(word + i ) + 1;
            strcpy_s(word + i + 2, size_of_word, word + i);
        }
        else 
        {
            i++;
        }
    }

    cout << word;
}
jpo38
  • 20,821
  • 10
  • 70
  • 151
Bogdan Lica
  • 23
  • 1
  • 6

1 Answers1

2

As commented, prefer std::string to char arrays, they are easier to use.

If you can't use them:

strcpy_s second parameter is the size of the destination buffer, whiwh is different than the size of the string.

word buffer size is 202, so, word + i + 2 buffer size is 202-i-2, not size_of_word

size_of_word = size_t(word + i ) + 1; sets size_of_word to [address of word buffer] + i + 1 which does not make any sense...

This should work (I moved buffer size to a variable to make it easier to be changed):

#include <iostream>
#include <cstring>
#include<conio.h>
using namespace std;
int main()
{
    int  i;
    static const size_t bufferSize = 202;
    char word[bufferSize];
    cin.get(word, bufferSize - 1, '\n');
    cin.get();
    i = 0;
    while (i < strlen(word) - 1)
    {
        if (word[i] == word[i + 1])
        { 
            strcpy_s(word + i + 2, bufferSize - i - 2, word + i);
        }
        else i++;
    }

    cout << word;
}
jpo38
  • 20,821
  • 10
  • 70
  • 151