2013-08-03 36 views
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" 

自上次读出字存储到同一个字符数组的开始这是不是很奇怪。有没有简单的解决方案?

+2

多少个变量是你允许使用?这是家庭作业还是减少变量试图解决一个未阐明的基本问题(例如堆栈溢出)? – simonc

回答

2

您正在将每个单词分配到缓冲区的相同地址,因此它们将首先被汽车覆盖,然后由猫覆盖,最后由循环覆盖。

尝试使用二维数组,一维是它包含哪个单词,另一个是它将容纳多少个字符,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个字符。

+4

您可以将格式说明符更改为'%20s'来限制写入的字符串的最大长度。 – simonc

+0

是的,我即将测试它 – nio

+0

在这个线程很多很好的答案。我选择了这个,因为它是最简单的一个。用可行的解决方案给其他人+1。 – user1319951

0

你说你只能使用一个变量。而不是让一个变量为单个字符串(字符数组),使它成为一个字符串数组(char数组)。

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]); 

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

1

这是一个糟糕的方式,但仍:如果输入名字都保证有字母少于一定数量时,就像9

只需使用随机尺寸输入字符串

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); 
0

,你可以使用这个:

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); 
3

使用循环?

char buf[0x100]; 

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

旁注:但是为什么不一次读整行,然后使用e来解析它。 G。 strtok_r()

fgets(buf, sizeof buf, stdin); 

是要走的路...

+0

+1由于循环应该是第一个考虑的选项,因此只能看到1个循环的回答令人伤心。另外,'fgets()'一次性解决了I/O和缓冲区溢出问题。 – chux

+0

@chux是的,接受的答案是简单的**。** :-( – 2013-08-03 13:48:32

+0

顺便说一句,OP有100,你有0x100 - 你的标准缓冲区大小。 – chux

0

你可以使用2-d数组:

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]); 
相关问题