Octavian Niculescu
Octavian Niculescu

Reputation: 445

Insert a word in an array of chars if I find a space

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.

Upvotes: 0

Views: 243

Answers (2)

A M
A M

Reputation: 15277

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

Upvotes: 1

Rohan Bari
Rohan Bari

Reputation: 7726

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

Upvotes: 0

Related Questions