我有以下代码来计算输入字符串中每个字母的出现次数。while循环可以正确执行。现在我有了包含arr[0]中‘a’、arr[1]中‘b’的数量的arr[],依此类推。
但是,以下printf不会显示arr的完整内容。(示例o/p如下所示)。
如果我完全注释掉while循环,printf会打印出所有26个arr[]值!在这个简单的程序中,我会遗漏什么?
如果它有任何帮助,我正在使用VS2008。
int arr[26]={'\0'};
int i = 0, c = 0, idx = 0, count = 0;
while( (c = getchar()) != EOF ) {
if( 'a' <= c && 'z' >= c ) {
idx = c - 'a';
arr[idx] = arr[idx]+1;
}
}
for(count = 0; count < 26; count++) {
printf("arr[%d] = %d\n", count, arr[count]);
}我得到的输出(对于不同的输入会保持不同):
abcxyz
arr[0] = 1
arr[1] = 1
^CPress any key to continue . . .
abcabc
arr[0] = 2
arr[1]
^CPress any key to continue . . .@Nobilis:更新代码以解决大写字母,也使打印更有意义:)
int main()
{
int arr[26]={'\0'};
int i = 0, c = 0, idx = 0, count = 0;
while( (c = getchar()) != EOF )
{
if( 'a' <= c && 'z' >= c )
{
idx = c - 'a';
arr[idx] = arr[idx]+1;
}
if( 'A' <= c && 'Z' >= c )
{
idx = c - 'A';
arr[idx] = arr[idx]+1;
}
}
for(count = 0; count < 26; count++)
{
printf("%c or %c = %d\n", ('A'+count), ('a'+count), arr[count]);
}
}发布于 2013-07-20 16:45:33
当你想结束输入字符时,在linux上按CTRL-D,在windows上按CTRL-Z,而不是CTRL-C。
CTRL-C会终止程序,因此不会再进行任何处理,您将看不到输出。
https://stackoverflow.com/questions/17760336
复制相似问题