簡體   English   中英

如何從Linux命令行接受C語言中的標准輸入

[英]How to Accept Standard Input in C from the Linux Command Line

我正在嘗試從Linux中的標准輸入接受一個字符串,采用給定的字符串並將'A'和'a'更改為'@',然后輸出更改后的字符串。

在linux中,我正在運行此命令:echo“此問題很容易解決” ./a2at

我的a2at.c程序包含以下內容:

#include <stdio.h>
#include <string.h>

int main(int argc, char *words[])
{   

    int i = 0;
    char b[256];

    while(words[i] != NULL)
    {
    b[i] = *words[i];

        if(b[i] =='a' || b[i]=='A')
          {
           b[i] = '@';
          }

    printf("%c",b[i]);
    }
    return 0;

}

任何幫助將非常感激! 我知道我離正確的代碼還差得很遠。

您可以使用getchar()一次讀取一個字符,或者使用fgets()每次讀取完整的一行。

最簡單的解決方案是在簡單的無限循環中使用getch

while (1) {
    int ch = getchar();
    if (ch == EOF) {
        break;
    } else if (ch == 'a' || ch == 'A') {
        putchar('@');
    } else {
        putchar(ch);
    }
}

正如@BLUEPIXY在他的評論中所說,您可以使用stdio.h中的getchar函數,只需在shell中使用man getchar以獲得有關用法的更多詳細信息。 這段代碼可以為您提供幫助,但是請不要猶豫使用man命令:)!

#include <stdio.h>

int main(void)
{
  int c;

  while ((c=getchar()) && c!=EOF) {

     if (c == 'a' || c== 'A')
       c = '@';

     write(1, &c, 1); // Or printf("%c", c);

    }

  return (0);

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM