[英]Assigning a user-entered char to a variable
我遇到一些問題,無法成功將用戶輸入的char
存儲到變量中,然后需要在程序的其他部分中使用該變量。
有問題的程序應該執行以下操作:
我將在這里以代碼片段的形式向您展示該程序的第二部分,因為第一部分(將值放入數組中)可以正常工作:
char input, confirm;
printf("Would you like to view the array? Y/N: ");
while ((input = getchar()) != EOF){
confirm = putchar(input);
if (confirm == 'Y'){
printf("[");
for (i = 0; i < maxvals; i++){
if (i != maxvals - 1){
printf("%d,", A[i]);
}
else{
printf("%d", A[i]);
}
}
printf("]");
}
printf("\n");
所有變量顯然都是預先聲明的。 第2行和第3行是我現在遇到的問題。
當我嘗試運行該程序時,我得到:
$ arrays.exe
Enter as many as 10 values, ^D to end
1 2 3
^D
3 values read into array
Would you like to view the array? Y/N: ♦
Y
Y
請注意該程序只是重復用戶輸入的內容。 我也嘗試了這個(代替while循環):
confirm = getchar();
但這只是終止程序。 我也擔心我的if (confirm == "Y")
行不起作用,但是根據我以前的編程經驗,我認為應該行嗎?
我很確定我已經給出了所有必要的代碼,但是如果您想要整個程序,請告訴我,以便我進行編輯。
編輯:
沒有人提到scanf。 它解決了問題。 這是工作代碼,以備將來參考:
while (scanf("%c", &confirm) == 1){
if (confirm == 'Y'){
printf("[");
for (i = 0; i < n; i++){
if (i != n - 1){
printf("%d,", A[i]);
}
else{
printf("%d", A[i]);
}
}
printf("]");
break;
}
}
return 0;
您說它不起作用,但您沒有說不起作用的症狀是什么。 這可能會有所幫助。 無論如何,我認為有兩件事可能是問題:
putchar(input)
沒有做任何有用的事情。 putchar
不會將值寫入變量(您嘗試分配以confirm
),而是將其寫入程序的標准輸出(完全不是同一件事)。 我認為您根本不想使用putchar
。 confirm
是一個char
,則要與'Y'
(一個字符)而不是"Y"
(一個字符串)進行比較。 查看confirm
如何聲明可能會有所幫助。 這是您要嘗試執行的簡化示例。 除非您正在從文件中讀取輸入(除了cntrl + c或退出按鈕,如果您正在使用控制台應用程序),否則eof字符為'\\ 0',因此無法停止此循環。 必須將字符與單引號中的字母進行比較。 另外,如先前的海報所述,putchar並沒有達到您的預期。 這是有關該功能的文檔: http : //www.cplusplus.com/reference/cstdio/putchar/
int main()
{
char input, confirm;
printf("Would you like to view the array? Y/N: ");
while ((input = getchar()) != EOF){
if (input == 'Y'){
printf("!");
}
}
return 0;
}
here is your code, cleaned up some
and not using a 'input' variable
and not using a call to putchar()
and 'confirm' properly declared as an int
// this assumes that A[] and maxvals and i are already defined and set
int confirm;
printf("Would you like to view the array? Y/N: ");
while ((confirm = getchar() && !( 'Y' == confirm || 'N' == confirm ) && EOF != confirm )
{
if( EOF == confirm ) exit(1);
else printf( "invalid input: please enter: 'Y' or 'N'");
} // end while
// when get here, confirm contains 'Y' or 'N'
if ( 'Y' == confirm )
{
printf("[");
for (i = 0; i < maxvals; i++)
{
if (i != maxvals - 1)
{
printf("%d,", A[i]);
}
else
{
printf("%d", A[i]);
} // end if
} // end for
printf("]");
} // end if
printf("\n");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.