我在随机字符串()中有一个for循环,它将一个随机字符放入字符串的前x个索引中,其中x<;是字符串长度.然后,我在字符串中添加一个‘\0’,并使用printf()打印它,但它打印的字符比x多1个字符,并且该字符总是相同的,我不知道为什么.
这是我拥有的代码:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#define NELEMS(x) sizeof(x)/sizeof(x[0])
#define MAX_LENGTH 25
void randomChar();
void randomString();
int main()
{
srand(time(NULL));
int points = 0;
randomString(&points, 3);
return EXIT_SUCCESS;
}
void randomString(int *points, int length)
{
char input[MAX_LENGTH], output[MAX_LENGTH];
do
{
int i;
for (i = 0; i < length && i < NELEMS(output)-1; i++)
output[i] = (char)(rand() % 26 + 97);
output[i+1] = '\0';
//output[i+2] = '\0';
// for (int i = 0; i < NELEMS(output)-1; i++)
// output[i] = i < length ? (char)(rand() % 26 + 97) : '\0';
printf("You have %d points, type %s:\n", *points, output);
scanf("%s", &input);
strcmp(input, output) == 0 ? *(points)++ : *(points)--;
getchar();
} while (input[0] != '@');
}
我一直在try 这个长度为3的函数,得到一个结果:
You have 0 points, type opc♦:
a
You have 0 points, type lbu♦:
a
You have 14488832 points, type wal♦:
使用output[i+1] = '\0'
和output[i+2] = '\0'
解决不了任何问题
注释掉的for循环可以工作,但我不知道为什么第一个循环不能工作
你知道为什么它多印了一个字符吗?
哦,如果你知道为什么14488832出现在输出中,我也想知道.
编辑:
DBush用(*Points)++而不是*(Points)++修复了指针错误,但在3个字母字符串之后打印另一个字符的第一个错误仍然存在:
You have 0 points, type opc♦:
a
You have 0 points, type lbu♦: