使用switch语句

时间:2015-06-13 16:42:50

标签: c memory

我无法计算用户使用switch语句输入的单词数。我想确保多次按键盘(ASCII,32)不计入多个单词。正如你所看到的,我有一个内存变量存储以前的键盘按下,我想只计算一个单词当前键盘按下是一个空格,而前一次按下(即内存变量不是空格)。逻辑对我来说很有意义;但是,代码似乎不起作用。有人可以解释我的逻辑缺陷在哪里吗?感谢。

// 1.4 Exercise 1: output the amount of characters, number of words and number of newlines typed by the user 
// Note that the escape command on my mac is ENTER then COMMAND Z
#include <stdio.h>

int main()
{
    long characters = -1; // to exit program on my mac you must press COMMAND+Z 
    long newlines = 0;
    long words = 1; // assume the document starts with a word 

    printf("Type stuff! To exit type CTRL+D (some computers use CTRL+Z then space)\n");

    int i = 0;
    int memory = 32; //stores the previous keyboard press 


    while (i != EOF) // characters will continue counting as long as the escape sequence is not entered 
    {
        i = getchar(); //Assign the integer output of the buffered getchar() function to i 

        if (i != 10)
        {
            characters++;
        }

        switch (i)
        {
        case 10: // for enter key press
        {
            newlines++;
            break; // exit switch (each character is unique) 
        }
        case 32: // for space 
        {
            if (memory != 32) // if the previous character press was not a space, then words++
            {
                words++;
            }
            memory = i; // stores the previous keyboard press
            break; // exit switch (each character is unique) 
        }
        default: break; //exit switch is the default action if the previous switches are not true 
        }
    }

    printf("%d characters were typed\n", characters);
    printf("%d words were typed\n", words);
    printf("%d lines were typed\n", newlines);

    return 0;
}

2 个答案:

答案 0 :(得分:2)

当i = 32时,只在case语句内部更新内存值。这样,内存的值将始终为32.相反,应该在switch语句关闭后更新内存值。即。

switch(i)
{
    /* code here */
}
memory = i

作为旁注,如果您不将字符的ascii值硬编码到switch语句中,它将使您的代码更具可读性并有助于实现可移植性。您可以使用该字符来编写它们。

switch(i) 
{
    case '\n':
        /* code */
        break;
    case ' ':
        /* code */
        break;
}

答案 1 :(得分:0)

您无条件地必须存储前一个字符:

 memory = i;

另外,考虑角落情况,例如:当一行中只有一个单词(没有空格)时会发生什么。如您所见,不仅空格可以分隔单词。