Monday, May 24, 2010

Another C++ Question?

Sort and output an array of inputted characters, based on their number of occurrences (from highest to lowest). What's wrong with this code?





#include %26lt;iostream%26gt;


#include %26lt;fstream%26gt;





int main(void)


{


using namespace std;





char chars[]="abcdefghijklmnopqrstuvwxyz";


int i;


int count[]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0...





char inp;





cin%26gt;%26gt;inp;





while(inp !='.')


{


for(i=0;i%26lt;26;++i)


{


if(inp==chars[i])


count[i]++;


}


cin%26gt;%26gt;inp;


}





int swap;


char swapchar;





for(i=0; i%26lt;26; ++i)


{


if (count[i] %26gt; count[i + 1])


{


swap = count[i];


count[i] = count[i + 1];


count[i + 1] = swap;





swapchar = chars[i];


chars[i] = chars[i + 1];


chars[i + 1] = swapchar;


}


}





cout%26lt;%26lt;"Character Count"%26lt;%26lt;endl;








for(i=0;i%26lt;26;++i)


{


if(count[i]!=0)


{


cout%26lt;%26lt;chars[i]%26lt;%26lt;" "%26lt;%26lt;count[i]%26lt;%26lt;endl;


}


}





system("pause");





return 0;


}

Another C++ Question?
You put your using statement inside main().
Reply:Well first of all your namespace position is incorrect... it should be after #include%26lt;fstream%26gt;, you don't need fstream since you are not doing any file streaming.





Second, check your braces... { and } i tried fixing your program and it doesnt work actually because of the errors... your swap or as we call it "Bubble sort" is ok... but change the limit from 26 to 25 since you'll be comparing the second to the last. Also, you'll have to put that in another loop since you need to do that 25 times again since you'll only be pushing one lowest number at a time... you should also try considering if there are equal times it appeared.





Note: I didn't fix it to work... i want you to handle that part. ^^, i'm just here to correct a few errors =)


No comments:

Post a Comment