2013-10-04 19 views
2

我是一名初級程序員,正在學習一門課,並且無法讓我的輸出字符串在單詞之間打印空格。以下是我的代碼如下。它應該接受一個我輸入的字符串,並且當我運行該程序時指定爲全部大寫或全部小寫。如果我放入我的代碼不工作,它會輸出mycodedoesnotwork。爲什麼要刪除空格?程序正在刪除字符串中的空格uninteded

1 #include <stdio.h> 
2 #include <assert.h> 
3 #include <stdlib.h> 
4 #include <string.h> 
5 
6 
7 int shout(char * msgIn, char * msgOut) { 
8 
9   if (!msgIn || !msgOut) 
10     return -1; 
11   while (*msgIn != '\0') { 
12     if ('a' <= *msgIn && *msgIn <= 'z') 
13       *msgOut = *msgIn + ('A' - 'a'); 
14     else 
15       *msgOut = *msgIn; 
16     msgIn++; 
17     msgOut++; 
18   } 
19   *msgOut = '\0'; 
20 
21   return 0; 
22 } 
23 
24 
25 int whisper(char const * msgIn, char * msgOut) { 
26   if (!msgIn || !msgOut) 
27     return -1; 
28   while (*msgIn != '\0') { 
29     if ('A' <= *msgIn && *msgIn <= 'Z') 
30       *msgOut = *msgIn + ('a' - 'A'); 
31     else 
32       *msgOut = *msgIn; 
33     msgIn++; 
34     msgOut++; 
35   } 
36   *msgOut = '\0'; 
37   return 0; 
38 } 
39 
40 int main(int argc, char ** argv) { 
41   char in[128], out[128]; 
42   int i; 
43   for (i = 1; i < argc; i++) { 
44     if (strcmp("-w", argv[i]) == 0) 
45       while (scanf("%s", in) != EOF) { 
46         whisper(in, out); 
47         printf("%s", out); 
48       } 
49     else if (strcmp("-s", argv[i]) == 0) 
50       while (scanf("%s", in) != EOF) { 
51         shout(in, out); 
52         printf("%s", out); 
53       } 
54   } 
55   printf("\n"); 
56   return 0; 
57 } 

+0

啊!請從代碼中刪除行號。 – Sadique

+0

我想這會有所幫助,所以有人可以指定他們指的是哪一行,但我會注意到您的請求。 –

+0

您認爲scanf有什麼作用? –

回答

2

scanf調用閱讀只是的話(無空格),您不添加空格回來,當你輸出你的字符串。

如果你不介意尾隨空間,只是改變線47和52 printf("%s ", out)

+0

感謝修復奧利弗。這將對我今天晚些時候的任務有所幫助,但我會檢查我的未知scanf並用不同的方法重做它。 –

1

while (scanf("%s", in) != EOF) ==>scanf()需要輸入最多的空間,發送到恢復工作

,然後在下次迭代在空間之後採取詞。

您需要改爲使用fgets()

+0

我會研究這個。這本書還沒有結束fgets(),所以暗示它必須要用scanf來完成。我會研究這個。謝謝你的提示。 –

+0

它取決於你。現在只要看到link.there你會發現實現。 – Gangadhar

0

這與您的shout()wisper()函數沒有問題,但問題與scanf()

當您指定%s閱讀字符串,字符串將終止在任何空白字符 - 空格,製表等

而且不會被列入的字符串中。因此,您在字符串之間輸入的空間不存儲在in變量中。

你可能想要想出不同的方法來解決這個問題。

+0

這是本書向我們展示閱讀字符串並使用它們的唯一方式,因此這是我唯一的方法。我會研究fgets()。這本書有點欠缺。謝謝回覆。 –

0

空間scanf()scanf()的字符串終結符,它不包含在獲取的字符串中。 man 3 scanf