2016-02-14 55 views
0

我試圖從Linux的標準輸入接受一個字符串,接受給定的字符串並將'A'(s)和'a'(s)更改爲'@',並輸出改變的字符串。如何從Linux命令行在C中接受標準輸入

在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; 

} 

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

+1

你的問題是? – fuz

+4

使用'getchar()'。 – BLUEPIXY

+0

這段代碼很不正確。接受來自linux命令行的標準輸入的正確語法是什麼?我想獲取一個字符串並更改一些字符,然後顯示新的字符串。 – Np938

回答

0

由於@BLUEPIXY在他的評論中說,你可以使用getchar函數stdio.h中,只是做男人的getchar在你的shell有更多關於使用的細節。這段代碼可以幫助你,但不要猶豫,使用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); 

} 
1

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

最簡單的解決方案將是一個簡單的無限循環使用getch

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

非常感謝! – Np938

相關問題