我想從用戶那裏得到一個輸入,並對該輸入進行冒泡排序然後輸出結果。我的代碼:如何使用其他值對空格進行冒泡排序?
#include<iostream>
using namespace std;
class bubble
{
public :
string arr[20];
//Number of elements in array
int n;
//Function to accept array elements
void read()
{
while(1)
{
cout<<"\nEnter the number of elements in the array:";
cin>>n;
if(n<=20)
break;
else
cout<<"\n Array can have maximum 20 elements \n";
}
//display the header
cout<<"\n";
cout<<"----------------------\n";
cout<<"Enter array elements \n";
cout<<"----------------------\n";
//Get array elements
for(int i=0; i<n ;i++)
{
cout<<"<"<<i+1<<"> ";
cin>>arr[i];
}
}
//Bubble sort function
void bubblesort()
{
for(int i=1;i<n ;i++)//for n-1 passes
{
//In pass i,compare the first n-i elements
//with their next elements
for(int j=0; j<n-1; j++)
{
if(arr[j] > arr[j+1])
{
string temp;
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
void display()
{
cout<<endl;
cout<<"----------------------\n";
cout<<"Sorted array elements \n";
cout<<"----------------------\n";
for(int j=0; j<n; j++)
cout<<arr[j]<<endl;
}
};
int main()
{
//Instantiate an instance of class
bubble list;
// Function call to accept array elements
list.read();
// Function call to sort array
list.bubblesort();
//Function call to display the sorted array
list.display();
return 0;
}
代碼運行良好,但它不接受字符串中的空格或縮進值作爲輸入。有沒有辦法讓它接受這些值?
'cin'被標記化的,這意味着它根據一組定界符的分裂輸入。這些分隔符默認爲空格。 – maddin45