2011-08-23 49 views
0

以下问题:让字符串增长输入

我想做一种hang子手游戏(控制台中的所有东西)。 所以我做了一个循环,在游戏结束后会变成13次,玩家松动(如果玩家插入错误的字母,它只会倒数)。 现在,我想向用户显示他已使用哪些字母。所以输出应该是这样的:“你已经使用过:a,b,c,g ...”等等。所以在每次尝试之后,该行都会增长一个字母(当然是输入字母)。 我试过strcpy,但它只会产生随机字母,我从来没有放过,它不会增长,所以我该如何处理?

#include <stdio.h> 
#include <conio.h> 
#include <stdlib.h> 
#include <string.h> 
#include <windows.h> 
#include <ctype.h> 

void gotoxy(int x, int y) 
{ 
COORD coord; 
coord.X = x; 
coord.Y = y; 
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord); 
} 

int main() 

{ 
char word[81], used[14]; 
int wrong=0, laenge, _, i; 
char input; 


SetConsoleTitle(" Guess me if u Can! "); 



//printf("\n\n spielst du mit einem Freund oder alleine?"); /*for later 
//printf(" \n\n [1] alleine" 
//  " \n\n [2] mit einem Freund");         */ 


printf("\n\n please insert a word (max. 80 characters): \n\n"); 

gets(word); 

    laenge=strlen(word); 

    printf("\n\n this word has %i characters.\n\n",laenge); 

    for(i=0; i<13; i++) 
    { 
//     for(_=0; _<laenge; _++) /*ignore this this is also for later 
//     printf(" _"); 
//     printf("\n");           */ 

    gotoxy(10,10); 
    printf("\n\n please insert a letter now: "); 
    input=getch(); 
    strcpy(used, &input); 
    printf("\n\n The following characters are allready used: %c ", used); 

    if(strchr(word, input)){ 
         printf("\n\n %c is in the word\t\t\t\t\t\t\n\n"); 
         i--; 

    } 
        else{ 
         printf("\n\n the letter %c is wrong!\n"); 
         wrong++; 
         printf(" you have %i try",13-wrong); 
    } 

    } 
    system("cls"); 
    printf("\n\n to many tries.\n\n"); 





system("Pause"); 


} 
+2

边注:从来没有使用的变量名与'_'开始(他们可能会使用系统变量冲突)。更少一个'_'。 –

+0

这就是为什么我总是使用带有字符串的语言。 –

回答

1

正如已经在这里说,你应该用零填充使用,像used[14] = {0};

然后,我觉得行printf("\n\n The following characters are allready used: %c ", used);应该printf("\n\n The following characters are allready used: %s ", used);,请注意“%s的”你打印的字符串。

+0

谢谢你这是'%s'发生这种情况,如果你在代码上寻找几个小时,并试图找到我眼中有blinkers的错误 – globus243

2

首先,你应该填补used有0个字符,以确保它始终是正确的终止:

memset(used, 0, 14); 

然后,添加一个新的角色,以这样的:

used[i] = input; 

另外,如@Fred所述,您应该在printf调用中使用适当的格式说明符%s

0

如果知道最大大小,则可以创建一个具有该最大大小的缓冲区,然后将其附加到该缓冲区。在这种情况下,您确实知道最大尺寸,因为字母表中只有26个字母。因此,字符串的最大长度是您在开头放置的任何文本的长度,加上您将用于每个字母的字符数的26倍。我在初始字符串中计数了18。请记住在结尾处为空字节终止符添加一个。对于每个字母,你都有字母,逗号和空格,所以如果我进行了算术计算,则最大长度为18 + 26 * 3 + 1 = 97。

所以,你可以写这样的:

char used[96]; 
strcpy(used,"You already used: "); 
int first=TRUE; 
... whatever other work ... 
... let's say we get the character in variable "c" ... 
// Add comma after previous entry, but only if not first 
if (!first) 
{ 
    first=FALSE; 
    strcat(used,", "); 
} 
// turn character into a string 
char usedchar[2]; 
usedchar[0]=c; 
usedchar[1]='\0'; 
// Append to working string 
strcat(used,usedchar); 
+0

从技术上来说,因为它只会在玩家输掉之前增加13个字符,他真的只需要做18 + 13 * 3 + 1 = 58 – Daniel

+0

好点,我在“13转”中掠过。 – Jay