[英]Printing Array in C++
我在運行代碼時包含了我的屏幕截圖,您可以查看原始數組和排序數組的末尾。 在我打印原始數組和排序后的數組后,我總是在數組的末尾得到一些符號。 我怎么能解決這個問題?
#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;
}
這是我運行代碼后的截圖
我應該只得到數組而不是最后的那些符號。
打印字符數組時,最后需要 null character('\0') 終止。 否則,程序將不知道何時結束並繼續打印,直到找到 0。
int main() {
char arr[21];
arr[20] = 0;
...
}
在數組末尾添加一個 null 字符,它將起作用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.