【问题标题】:Printing Array in C++在 C++ 中打印数组
【发布时间】:2021-04-28 01:40:20
【问题描述】:

我在运行代码时包含了我的屏幕截图,您可以查看我的原始数组和排序数组的末尾。 在我打印原始数组和排序后的数组后,我总是在数组的末尾得到一些符号。我该如何解决?


    #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;
    }

这是我运行代码后的截图

我应该只得到数组而不是末尾的那些符号。

【问题讨论】:

    标签: c++ arrays sorting


    【解决方案1】:

    当你打印字符数组时,最后需要空字符('\0') 来终止。否则,程序将不知道何时结束并继续打印,直到找到 0。

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

    在数组末尾添加一个空字符就可以了。

    【讨论】:

      猜你喜欢
      • 2013-09-23
      • 2011-03-24
      • 2014-05-20
      • 1970-01-01
      • 2011-06-03
      • 2010-11-25
      • 2011-02-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多