[英]getchar() not returning any output
我正在瀏覽一些基本的 C 代碼,然后我找到了一個旨在從給定輸入中計算數字的程序:
#include <stdio.h>
// count characters given as input
int main()
{
double nc;
for(nc = 0; getchar() != EOF; ++nc)
;
printf("%.0f\n", nc);
}
但是當我在終端上運行程序時(我使用的是 Debian 11),我沒有得到任何 output 作為輸入。 但是按 Ctrl+C 會終止程序。
我不得不稍微修改你的代碼以使其工作
#include <stdio.h>
#include <signal.h>
static volatile int keepRunning = 1;
void intHandler(int dummy) {
keepRunning = 0;
}
// count characters given as input
int main()
{
int nc = -1;
signal(SIGINT, intHandler);
while (keepRunning) {
nc = 0;
for(nc = 0; getchar() != EOF; ++nc)
;
}
if(nc != -1)
printf("%i", nc);
}
按 ctrl + c 將在打印 nc 之前終止程序,所以我們必須抓住用戶按 CTRL+C,唱信號庫
看到這個: Catch Ctrl-C in C
我正在使用Win10,MS編譯器,它工作得很好......
C:\Users\Ahmed\Desktop>cl test.c
Microsoft (R) C/C++ Optimizing Compiler Version 17.00.50727.1 for x86
Copyright (C) Microsoft Corporation. All rights reserved.
test.c
Microsoft (R) Incremental Linker Version 11.00.50727.1
Copyright (C) Microsoft Corporation. All rights reserved.
/out:test.exe
test.obj
C:\Users\Ahmed\Desktop>test.exe
adkjlad
asldkjasd
18
C:\Users\Ahmed\Desktop>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.