作为初学者,我试图以单词形式输入一位数字,但将它们排序并显示为数字。
输入时:
七三五一无
输出是
0 1 3 5 7 我怎样才能阻止 0 显示和首先填充到 num 数组中?
#include <iostream>
#include <algorithm>
#include <string>
#define n 5
using namespace std;
string words[n];
int nums[n],size;
void input(){
cout<<"Enter in word form, the numbers to be sorted\n";
for( int i = 0; ; i++){
cin >> words[i];
if( words[i] == "nil" )
break;
}
size = sizeof words/sizeof(string);
}
void convert(){
for( int i = 0; words[i]!= "nil" ; i++ ){
if ( words[i] == "one" )
nums[i] = 1;
//
else
cout<<"Wrong input\n";
}
}
void sort(){
sort(nums, nums + size);
for ( int i = 0; i < size; i++ )
cout<< nums[i]<<endl;
}
int main(){
input();
convert();
sort();
system("pause");
return 0;
}
这很好用,我在单词长度上犯了错误..为了从排序的考虑中删除元素 nil (用作哨兵),我必须将大小减小 1 。这段代码工作得很好,并且按照它的预期方式工作。
//headers and std
string words[n];
int nums[n],size;
void input(){
cout<<"Enter in word form, the numbers to be sorted\n";
for( int i = 0; ; i++){
cin >> words[i];
if ( words[i] == "nil" )
break;
}
size = sizeof words/sizeof(string) - 1;//one for nil
}
void convert(){
for( int i = 0; words[i]!= "nil" ; i++ ){
if ( words[i] == "one" )
nums[i] = 1;
else if ( words[i] == "two")
//
}
}
void sort(){
sort(nums, nums + size);
for ( int i = 0; i < size; i++ )
cout<< nums[i]<<endl;
}
int main(){
//
}