簡體   English   中英

為什么我在 char 數組的末尾得到 i?

[英]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;
}

輸入:

10
Ajith@#

預計 output:

Ajith

Acutal output 我得到:

Ajithi

為什么我在數組的末尾得到我? 我只需要打印忽略數字和特殊符號的字母。 請幫我解決這個問題

您告訴程序輸入將是十個字符,包括空終止符。

然后你只輸入七個字符。 空終止符留下數組的兩個未初始化元素,這兩個元素將具有不確定的值。

您的循環仍然使用所有十個字符,並且以任何方式使用不確定的值都會導致未定義的行為

可能發生的情況是,在您的程序認為是字符的空終止符之后有一些數據。

解決方案是std::string並且只迭代字符串的實際長度,復制到另一個std::string

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM