我是一名初学者程序员,我不能让我的输出字符串在单词之间用空格打印。这是我的代码如下。它应该采用我输入的字符串,并且在运行程序时指定所有大写或全部小写。如果我输入我的代码不工作,它会输出mycodedoesnotwork。为什么删除空格?
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 :(得分:2)
scanf
调用正在中读取单词(无空格),并且在输出字符串时不会再添加空格。
如果您不介意尾随空格,只需将第47和52行更改为printf("%s ", out)
答案 1 :(得分:1)
答案 2 :(得分:0)
您的shout()
或wisper()
功能没有问题,但scanf()
存在问题。
当您指定%s
来读取字符串时,该字符串将终止于任何空格字符 - 空格,制表符等。
这不会包含在字符串中。因此,您在字符串之间输入的空格不会存储在in
变量中。
您可能想要采用不同的方法来解决这个问题。
答案 3 :(得分:0)
space 是scanf()
的字符串终结符,scanf()
不包含在获取的字符串中。 man 3 scanf