简体   繁体   中英

why I am getting i at the end of char array?


#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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM