0

copy x to y without header files string.h

copy array of char to another without strcpy in c++

input : car a car

i want output without space or garbage : caracar

but ouput contain garbage or if i put : y[50]={0} ouput is one ward just output iscar just

i want output without garbage and "caracar"

#include <iostream>
#include <stdio.h>
using namespace std;

int main() {
   int i;
   char x[50], y[50] ;
   cout << "Enter : ";
   scanf_s("%[^\n]", x, sizeof(x));
   for (i = 0; x[i] != '\0'; i++)
       if ((x[i] >= 'a' && x[i] <= 'z') || (x[i] >= 'A' && x[i] <= 'Z'))
           y[i] = x[i];
   y[i] = '\0';

   cout << y;
}

output: caracar without space or grabage

6
  • What about using the Standard Library and not C headers? Commented Aug 22, 2021 at 14:45
  • 1
    Have you tried using the debugger and watch how the array elements are changed? Think about what happens when the condition is false. Commented Aug 22, 2021 at 14:46
  • Have a second iterator int j=0. Then use it to track write position. y[j++] = x[i]; Commented Aug 22, 2021 at 14:49
  • C or C++, pick one. Commented Aug 22, 2021 at 14:49
  • 1
    @AdrianMole I can manually fix the question, but it's also important to teach the OP so they can do it themselves. Commented Aug 22, 2021 at 14:54

5 Answers 5

1

Your problem is that you are using only a single 'index' variable (i) for both source and destination strings. However, you should only increment the destination index if you actually copy a character. As it stands, when the source character is not copied, you are still incrementing the destination index, so you are skipping characters in that buffer, which are left in their original (i.e. uninitialized/garbage) states.

You need a separate index (let's call it j) for your destination buffer; initialize that to zero (as with i) at the start of the for loop but only increment it if we actually copy something (this can be done best using the post-increment operator inside the [...] for the destination:

#include <iostream>
using namespace std;

int main()
{
    int i, j; // Need 2 index vars: one for source, one for destination
    char x[50], y[50];
    cout << "Enter : ";
    scanf_s("%[^\n]", x, static_cast<int>(sizeof(x))); // Note last argument is "int"
    for (i = j = 0; x[i] != '\0'; i++) // Set "j" to zero at loop start ...
        if ((x[i] >= 'a' && x[i] <= 'z') || (x[i] >= 'A' && x[i] <= 'Z')) {
            y[j++] = x[i]; // ...but only increment it on copy!
        }
    y[j] = '\0'; // Use Last "j" for position of nul terminator
    cout << y;
    return 0;
}
Sign up to request clarification or add additional context in comments.

Comments

1

Here is another solution. More C++-ish than working with raw arrays and indices, while being not as high level as using std::ranges::remove_copy_if:

#include <cctype>
#include <iostream>
#include <string>

int main()
{
    std::cout << "Enter : ";
    std::string x;
    std::getline(std::cin, x);

    std::string y;
    for ((unsigned char const e : x)
        if (std::isalpha(e))
            y.push_back(e);

    std::cout << y << '\n';
}

Additional credits: HolyBlackCat and Adrian Mole.

4 Comments

std::isalpha(e) is UB for negative character codes. Use std::isalpha((unsigned char)e), OR just change the type of e to unsigned char.
On the one hand you say while not relying on library functions but then use std::isalpha() in your code. If that ain't a "library function," then what is it?
@HolyBlackCat Thanks, will look into it and update the answer.
@AdrianMole Well okay, it is... I considered the core of the question to be "How to fill y given some condition?" I'll update the answer.
0

Seems your excercise is more 'C' but the solution would look something like this since you require not to use (which is not recommended for production code) :

int main()
{
    const size_t buf_size = 64;
    const char* input = "car a car";
    char output[buf_size];

    const char* input_ptr = &input[0];
    const char* output_ptr_end = &output[buf_size - 2]; // leave room for one extra trailing 0
    char* output_ptr = &output[0];

    while ((*input_ptr != 0) && (output_ptr < output_ptr_end))
    {
        if (*input_ptr == ' ') input_ptr++; // skip space
        *output_ptr++ = *input_ptr++;
    }
    *output_ptr = 0;
}

Comments

0

copy array of char to another without strcpy in c++

You can for example use std::ranges::copy.

without space

You can use std::ranges::remove_copy_if. Example:

auto is_space = [](char c) {
    return c == ' ';
};
std::ranges::remove_copy_if(x, y, is_space);

2 Comments

True, but manually writing a loop is a great learning exercise.
@HolyBlackCat Sure. It's just not necessary within the parameters of the given exercise. Learning to use the standard algorithms is also a great learning exercise.
0
char input[32];  // obtained text
char output[32];

char*in_pos     =   input;
char*out_pos    =   output;

for(char cur_char; (cur_char=*in_pos++); ) // while NULL not encountered
{
    if(
        (cur_char>='A'&&cur_char<='Z')|| // uppercase
        (cur_char>='a'&&cur_char<='z')|| // lowercase
        (cur_char>='0'&&cur_char<='9')   // digits
    )
        *out_pos++  =   cur_char; // output cur_char
}

*out_pos = 0; // NULL termination

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.