1

我要使用的变量数量有限,所以我想只使用一个变量来解决以下问题。是否可以?

  char str[100];
  // Type three words:
  printf("Type three words: ");
  scanf("%s %s %s",str,str,str);
  printf("You typed in the following words: \"%s\", \"%s\" and \"%s\"\n",str,str,str);

以下输入提供以下输出:

Type three words: car cat cycle
You typed in the following words: "cycle", "cycle" and "cycle"

这并不奇怪,因为最后读取的字存储在同一个字符数组的开头。有什么简单的解决方案吗?

4

7 回答 7

3

使用循环?

char buf[0x100];

for (int i = 0; i < 3; i++) {
    scanf("%s", buf);
    printf("%s ", buf);
}

旁注:但是为什么不一次读取整行,然后使用 eg 解析呢strtok_r()

fgets(buf, sizeof buf, stdin);

是要走的路...

于 2013-08-03T09:54:54.577 回答
2

您将每个字分配给缓冲区的相同地址,因此它们将首先被 car 覆盖,然后被 cat 覆盖,最后被循环覆盖。

尝试使用二维数组,一维是它包含哪个单词,另一个是它将容纳多少个字符,21 表示 20 个字符和一个零终止。

char str[3][21];
// Type three words:
printf("Type three words: ");
scanf("%s %s %s",str[0],str[1],str[2]);
printf("You typed in the following words: \"%20s\", \"%20s\" and \"%20s\"\n",str[0],str[1],str[2]);

此代码不会读取超过 20 行的字,从而防止缓冲区溢出和内存访问违规。scanf 格式字符串 %20s 会将读取限制为 20 个字符。

于 2013-08-03T09:53:15.283 回答
1

如果你知道单词可以有多长,你可以这样做:

scanf("%s %s %s",str,&str[30],&str[70]);

并通过以下方式显示:

printf("You typed in the following words: \"%s\", \"%s\" and \"%s\"\n",str,str[30],str[70]);

但它并不是真正优雅和安全。

于 2013-08-03T09:53:23.423 回答
1

这是最糟糕的方式,但仍然:

仅对输入字符串使用随机大小

char str[100];
  // Type three words:
  printf("Type three words: ");
  scanf("%s %s %s",str,str+22,str+33);
  printf("You typed in the following words: 
          \"%s\", \"%s\" and \"%s\"\n",str,str+22,str+33);
于 2013-08-03T09:53:32.173 回答
0

你说你只能使用一个变量。与其将一个变量设为单个字符串(char 数组),不如将其设为字符串数组(char 的二维数组)。

于 2013-08-03T09:53:06.053 回答
0

如果保证输入名称的字母小于某个数字,例如 9,则可以使用以下命令:

printf("Type three words: ");
scanf("%s %s %s",str,str + 10,str + 20);
printf("You typed in the following words: \"%s\", \"%s\" and \"%s\"\n",str, str + 10, str + 20);
于 2013-08-03T09:54:00.527 回答
0

您可以使用二维数组:

char str[3][30];

printf("Type three words: ");
scanf("%s %s %s", str[0], str[1], str[2]);

printf("You typed in the following words: \"%s\" \"%s\" \"%s\"\n", str[0], str[1], str[2]);
于 2013-08-03T10:01:02.080 回答