我是一名正在类的初学者程序员,我无法让我的输出字符串在单词之间带有空格的情况下打印。下面是我的代码。它应该采用我输入的字符串,并按照我在运行程序时指定的方式更改为全部大写或全部小写。如果我输入“我的代码不起作用”,它会输出“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 }
~
~
最佳答案
scanf
调用仅读取单词(无空格),并且在输出字符串时不会添加空格。
如果您不介意尾随空格,只需将第 47 行和第 52 行更改为 printf("%s ", out)
关于c - 程序意外删除字符串中的空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19178752/