简体   繁体   中英

Printing Array in C++

I have included my screenshot when running my code and you can look at the end of my original array and sorted array. After I print the original array and the sorted array I always get some sign at the end of the array. How could I fix that?


    #include<iostream>
    #include <algorithm>
    using namespace std;

    //Sort Function:
    void Sorted_Array(char fullarray[20])
    {
    int i, j, temp;
    for (i = 0; i < 20; i++) {
        for (j = i + 1; j < 20; j++) {
            if (fullarray[i] > fullarray[j]) {
                temp = fullarray[i];
                fullarray[i] = fullarray[j];
                fullarray[j] = temp;
            }
        }
        
    }
    cout << "Sorted Array is: " << fullarray<<endl;
    }
    

    //Frequent Function:
    void freq(char array[20])
    {
    int count[20],max,letter;
    max = 1; letter=0;
    
        for(int i=0;i<20;i++){
        count[i] = 0;
        for (int j = 0; j < i; j++) {
            if (array[i] == array[j]) {
                count[i]++;
            }
            if (count[i] > max) {       
                max = count[i];
                letter = i;
            }
        }               
        }
        if (max == 19) {
        cout << "All character entered are the same"<<endl;
     }
    else if (max == 1) {
        cout << "All character entered are different"<<endl;
    }
    else
        cout << "\n" "The most frequent letter is: " << array[letter] << " and Number of time it was entered is: " << max << endl;
    }



    int main() {
    char arr[20];
    cout << "Enter 20 alphabet: " << endl;
    for (int i = 0; i < 20; i++) 
    {
        cin >> arr[i];
            if (!isalpha(arr[i]))
                cout << arr[i] << " is not an alphabet" << endl;
                for (int j = 0; j < i; j++){
                    if (arr[i] == arr[j]){
                        cout << arr[i] << " is a duplicate letter." << endl;
                    }
                }       
    }
    system("cls");
    cout << "Array is: " << arr << endl;
    Sorted_Array(arr);
    freq(arr);
    system("pause");
    return 0;
    }

Here is my screenshot after running the code在此处输入图像描述

I should get only the array not those sign at the end.

When you print character array, you need null character('\0') at the end to terminate. Otherwise, program won't know when to end and keep printing until it finds 0.

int main() {
    char arr[21];
    arr[20] = 0;
    ...
}

Add a single null character at the end of the array and it will work.

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