gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 08:25:14 25 4
gpt4 key购买 nike

我无法计算用户使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com