gpt4 book ai didi

C 语言 Switch 语句不读取完整字符输入

转载 作者:行者123 更新时间:2023-11-30 19:37:10 32 4
gpt4 key购买 nike

我正在尝试编写一个 switch 语句来读取用户输入的报价。我遇到的问题是它只读取第一个字符并且程序退出。它需要达到所有字符输入并根据列出的条件进行测量。我是 C 语言新手,所以还没有进入数组阶段。我只需要一个指针来指出我哪里出错了!!

#include "stdafx.h"
#include <stdio.h>
#include <conio.h>
#include <ctype.h>
#include <string.h>

int main()
{

int c;
int temp = 0;
int ch;
int reader;

printf("Enter 1-read from keyboard or 2-read from file\n");
scanf_s("%d", &reader);

switch (reader) {

case 1:

printf("Please enter a quote\n");//user input characters

scanf_s("%c", &c);

while ((c = _getch()) !='\n'){ //reads each character and checks for end of line

printf("\n%c", c);


if (temp == c)

printf(" duplicate character");


if ((c) == 'a' || (c) == 'e' || (c) == 'i' || (c) == 'o' || (c) == 'u')

printf(" vowel is lower case");

if ((c) == 'A' || (c) == 'E' || (c) == 'I' || (c) == 'O' || (c) == 'U')

printf(" vowel is upper case");

if (ispunct(c))//checks for punctuation

printf(" punctuation");

temp = c;
break;

case 2:

printf("I need some help");
break;

default:



break;
}
}
return 0;
}

最佳答案

switch 语句很棘手...您的代码是删除填充行,如下所示:

switch (reader)
{
case 1:
while (getch(...))
{
//do things
break; // !!!!!!
case 2:
break;
default:
break;
}
}

查看带有感叹号的行。您可能会认为它破坏了 switch 但它实际上破坏了 while,因此您的程序结束了。

解决方案很简单,将 } 移动到该行之前的正确位置。或者更好的是,为情况 1 编写一个函数,为情况 2 编写另一个函数。

关于C 语言 Switch 语句不读取完整字符输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40224322/

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