私はCでメニュー入力プログラムを作成しています。ここでユーザー入力を求めてから、プログラムの入力の最初の文字のみを使用しなければなりません。以下のコードに加えて、私はまた、を試してみました。これは、とりわけ、の代わりに、while
ループの代わりに使用しました。Cでgetcharを使用して1文字を読み取る方法は?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void print_menu();
void uppercase(char *string);
int main()
{
char i = 0, c = 0;
char selection[0];
print_menu();
while((c = getchar()) != EOF)
{
selection[i++] = c;
selection[i] = '\0'; //insert NULL at end of string
uppercase(selection);
switch(selection[i])
{
case 'c':
uppercase(selection);
printf("%s\n", selection);
print_menu();
break;
case 'X':
printf("The program is exiting, Schuss!\n");
exit(0);
default:
printf("\nYou entered: %s\n", selection);
print_menu();
break;
}
}
return 0;
}
void print_menu() //gives code for menu
{
printf("Select a menu item and hit enter: \n");
printf("C) Convert the string to uppercase\n");
printf("M) Display this menu\n");
printf("X) Exit the program\n");
}
void uppercase(char *string)
{
int c = 0;
while (string[c] != '\0')
{
if (string[c] >= 'a' && string[c] <= 'z')
{
string[c] = string[c] - 32;
}
c++;
}
}
プログラムを実行しているとき、私はYes!
を入力すると、私は出力が You entered: Y
し、メニューのプリントであることを期待しています。 現在、出力が、私はそれがwhile
ループに問題がありますかなり確信して
You entered: Y
Select a menu item and hit enter:
C) Convert the string to uppercase
M) Display this menu
X) Exit the program
You entered: YE
Select a menu item and hit enter:
C) Convert the string to uppercase
M) Display this menu
X) Exit the program
You entered: S
Select a menu item and hit enter:
C) Convert the string to uppercase
M) Display this menu
X) Exit the program
You entered: S!
Select a menu item and hit enter:
C) Convert the string to uppercase
M) Display this menu
X) Exit the program
You entered:
Select a menu item and hit enter:
C) Convert the string to uppercase
M) Display this menu
X) Exit the program
^C
である、しかしそれを修正する方法を考え出したていません。最終的には、より多くのメニュー項目とケースがあります。たとえば、ユーザはA
を入力し、a
を印刷し、ユーザが終了するために「X」を入力するまで次のメニュー選択を待つためにメニューを再度印刷します。また、私はuppercase
の2つの関数呼び出しがあり、この時点で意図的であることを知っています。
編集:私はgetchar()
に1文字を読みたいと思っています。その後、その文字の大文字と小文字を区別します。次に、メニューをもう一度印刷します(この部分はそれぞれのcase文に含まれています)。次に、ステップ1(「1文字を読む」)から繰り返します。
私は、whileループの外getchar()
を入れて、一つだけの文字を読みになるんどの代わりwhile(1)
にループを設定するための私のコードを変更するだけでなく、You entered: B
を印刷する無限ループやメニューを作成しました。それは進歩です。
'char selection [0];'が間違っています。 switch(selection [i]) ' - >' switch(* selection) ' – BLUEPIXY
私はさまざまなサイズと同じ結果を試しました。私は配列のサイズを制限することが効果的だろうと思ったので、他のサイズが機能しなかったのでそのまま残しました。 –
ユーザーが入力した行全体を読み込み、最初の文字のみを使用したいとします。 'fgets'は入力行を読み込むのに適しています。読みやすさと理解を容易にするために –