c - 使用 switch 语句的字数统计程序在 C 中出错

标签 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;
}

最佳答案

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

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

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

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

关于c - 使用 switch 语句的字数统计程序在 C 中出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30821086/

相关文章:

c - 使用 fork/execvp 在 C 中编写一个简单的 shell

无法使用 `getpagesize()` 调用在 C 中设置全局变量

计算 char 数组中 1 和 0 的数量

java - JAVA中使用JNA时内存访问无效

php - 128MB 的 PHP 内存限制很多吗?

c - c库函数如何存放在内存中?

c - 哪些程序使用 GSS-API?有什么不错的示例程序吗?

c - 根据输入值将小单位输入转换为较高单位的最佳方法

c++ - std::vector 元素在物理内存中是否连续?

c++ - 1.exe : Microsoft C++ exception: std:out_of_range at memory location 0x0012fb8c中0x77e4bef7的未处理异常