0

I'm trying to insert a word where there is space (a character which ASCII code = 32, to be more clear) using strcat, like this.

Is there any way to insert a word where there is a space character in C?

#define _CRT_NONSTDC_NO_DEPRECATE

#include <iostream>

using namespace std;

int main()
{
    char a[100];
    cin.get(a, 100);
    for (int i = 0; i < strlen(a); i++)
    {
        if (a[i] == ' ')
        {
            strcat(a[i], "test ");
        }
    }
    cout << a;
}

In my mind this should work, but it actually doesn't. I get E0167 argument of type "char" is incompatible with parameter of type "char *".

Can I do this using strcat or is there any other way? Thanks.

kaylum
  • 13,833
  • 2
  • 22
  • 31
  • 1
    The warning is clear. `a[i]` is a `char` whereas `strcat` needs a `char *`. Try `&a[i]`. But note that this doesn't exactly "insert a word". It overwirtes the space and the characters after it with the replacement string. – kaylum Apr 25 '20 at 09:43
  • Yeah, you were right. I didn't get the expected result. Can you tell me a way to do what I wanted to? – Octavian Niculescu Apr 25 '20 at 09:50
  • There are many ways. Some better than others. Have you tried to do it on a piece of paper first with some examples to work out what operations are needed? That is, have you worked out the algorithm you want to use? I'll give you one simple way - use a second buffer, copy any characters that are not a space, if space, copy the insert word instead, continue til end of original string. – kaylum Apr 25 '20 at 09:55
  • I know how to do that using another array. (if that's what you mean by buffer, I'm not really good at C-style things, but that's what I'm doing at school rn lol). But I need a way to do that without adjacent arrays. Only modifying the original one. That's why I've tried to do it in that way. – Octavian Niculescu Apr 25 '20 at 10:08
  • As I said, how would you do it on a piece of paper? What do you need to do to make space to insert a word? – kaylum Apr 25 '20 at 10:17
  • Probably move some of the characters to the right to make space to insert that word. I would need to move each of the characters strlen(word to be added) positions to the right. I feel like this is a really complicated way to do it - there is probably another simpler one. – Octavian Niculescu Apr 25 '20 at 10:19
  • I think you will find your answer in the link below. [https://stackoverflow.com/questions/10030626/replace-char-in-string-with-some-string-inplace][1] – Ansel D'souza Apr 25 '20 at 10:41

2 Answers2

1

So, let us first analyze your program. Here are the findings:

  • You are using a mixture of C++ and C. You should decide for one language. You tagged the question with C++
  • Include file is missing
  • In my opinion you are still on C. But unfortunately, also this with bugs
  • using namespace std; shoulb be avoided. You can read many many posts here on SO about the why
  • Plain C-Style array like char a[100]; should not be used in C++. They are very error prone
  • For strings you should use std::string in C++
  • In you for loop you are mixing signed and unsigned values. std::strlen returns the unsigned type std::size_t
  • strcat should not be used. My compiler does not even compile it.
  • strcat with plain C-Style arrays is very dangerous and will often lead to undefined behaviour
  • The compiler already tells you one problem. strcat expects a char * as first element. You are giving it a char
  • strcat does not do what you expect. It always appends the 2nd parameter at the end of the string. Not on a certain position
  • So, even if you correct it to strcat(&a[i], "test ");, "test " will not be inserted at position i, but at the end of the string. Always leading to a desaster, if you enter a string with a length of 100 and spaces near the end.
  • There is not a single line of comment in the example
  • Variable names like 'a' have no meaning. Always use meaningful variable names
  • You are using i++ in your for loop. Always use ++i
  • Magic numbers like "100" should be avoided. Why 100? Whay not 99, 101 or 555?
  • Function main has been defined as int. It should return a value, e.g.return 0;

So, quite some problems in your code

We have the following categories of problems:

  • Hard syntax errors
  • Design errors
  • Semantic errors
  • Style errors

How to fix? Since we are still rather on C, experts like David should give the answer, but I will try to do my best. 2 Solutions:

  1. Continue with C-Style
  2. Write a C++ program

So, one of many possible examples for a C-Style solution

#include <iostream>
#include <cstring>

int main()
{
    // We want to work on a string with the maximum length of 0, including the terminating 0
    constexpr size_t MaxStringSize = 10U;

    // Here we will store the string in a C-Sytle char array
    char myText[MaxStringSize];

    // Now get the string from the user. Limit to a maximum length
    std::cin.get(myText, MaxStringSize);

    // We want to replace a space with the following text
    const char* replaceText = "test ";
    const size_t replaceTextLength = std::strlen(replaceText);

    // Now, iterate over all characters in the string given by the user and replace spaces
    for (size_t i = 0U; i < std::strlen(myText); ++i) {

        // Check, if the current character is a space, because then we need to replace
        if (myText[i] == ' ')
        {
            // We need space for the replacement text. So, we shift all characters at position i to the right
            // Caveats. The string array has a maximum length. We must not shift over the border
            if ((i + replaceTextLength +strlen(&myText[i])) < MaxStringSize) {

                // make free space
                std::memmove(&myText[i]+ replaceTextLength, &myText[i]+1, strlen(&myText[i])+1);

                // Copy replacement text
                std::memmove(&myText[i], replaceText, replaceTextLength);
            }
        }
    }
    // Show result to the user
    std::cout << myText;

    return 0;
}

And now the C++ solution. Using the C++ standard library.

#include <iostream>
#include <string>
#include <regex>

int main() {

    // Read a string from the user and check, if that operatrion was succesful
    if (std::string line{}; std::getline(std::cin, line)) {

        // Show text with replacements to the user
        std::cout << std::regex_replace(line, std::regex(" "), "test ") << "\n";
    }
    return 0;
}
A M
  • 14,694
  • 5
  • 19
  • 44
  • I'm using this mixture because that's what we do in school. I know it's bad, but we focus more on algorithms, so that's why we hardcode vectors to 100 too. I will look into your solution.Thanks. – Octavian Niculescu Apr 28 '20 at 07:50
0
#include <iostream>
#include <cstring> // use cstring not string or you'll be unable to use strlen() function

using namespace std;
const int N = 100;

int main(void)
{
    char str[100];

    cout << "Input a string: ";
    cin.get(str, N);

    for (int i = 0; i < strlen(str); i++)
    {
        if (str[i] == ' ')
        {
            str[i] = '_'; // change with your favorable char
        }
    }

    for (int j = 0; j < strlen(str); j++)
    {
        cout << str[j];
    }
    cout << endl;

    return 0;
}

Note: Better use a single width character to replace instead of a wide ones (e.g. "test " as char). The program might get more complicated if you want to do that. It's simple if you consider replace a space char to another char in a character array as string. I had searched over Stack Overflow, either you can replace a string to string, or char to char, but not a char (space) to a char array test.

Rohan Bari
  • 7,482
  • 3
  • 14
  • 34
  • Do not use ````using namespace std;````. "n" should be ````constexpr````. Your program does just replace one character. That is not what the OP asked. ````std::cout```can handle ````char*````. No need to print character by character. Please edit. – A M Apr 25 '20 at 19:27