0

#include<iostream>
#include<string.h>
using namespace std;
int main() {

    int n;
    cin>>n;
    char code[n];
    cin.ignore();
    cin.getline(code, n);

    int j=0;
    for(int i=0; i<n; i++) {

        if((code[i]>='A' && code[i]<='Z') || (code[i]>='a' && code[i]<='z')) {
            code[j] = code[i];
            j++;
        }
    }
    code[j] = '\0';
    cout<<code;
    return 0;
}

input :

10
Ajith@#

Expected output :

Ajith

Acutal output I'm getting :

Ajithi

why I am getting i at end of array ? I need to print only alphabets ignoring numbers and special symbols. please help me on this

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
Aj418
  • 11
  • 1
  • 1
    [Variable-length arrays are not really part of C++](https://stackoverflow.com/questions/1887097/why-arent-variable-length-arrays-part-of-the-c-standard), use `std::vector` instead. Or, in this case, `std::string`. – Some programmer dude Dec 11 '22 at 20:42
  • 1
    Also please learn about [`std::isalpha`](https://en.cppreference.com/w/cpp/string/byte/isalpha). – Some programmer dude Dec 11 '22 at 20:43
  • And that `ignore` call might not be enough. What if the user presses a lot of other characters after the number, but before the `Enter` key? – Some programmer dude Dec 11 '22 at 20:50
  • 1
    `std::string code;...code.erase(std::remove_if(code.begin(), code.end(), [](unsigned char c) { return !std::isalpha(c):}), code.end());` – PaulMcKenzie Dec 11 '22 at 20:55
  • `int n; ... char code[n];` You will never see arrays declared this way in any good C++ book. Why? Because this isn't valid C++. – PaulMcKenzie Dec 11 '22 at 20:58

1 Answers1

1

You tell the program that the input will be ten characters, including null-terminator.

Then you input only seven characters. With the null-terminator that leaves two uninitialized elements of the array, and those two elements will have indeterminate values.

Your loop still uses all ten characters, and using indeterminate values in any way leads to undefined behavior.

What is likely happening is that there's some data after the null-terminator that your program believes is characters.

The solution is std::string and only iterating over the actual length of the string, copying to another std::string.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • Or, at least, paying attention to how many characters `getline()` actually reads into the `char[]`, which is reported by `cin.gcount()`. – Remy Lebeau Dec 11 '22 at 21:29