求大神看看这个程序存字符串的时候问题出在哪里?

#include

#include

#define SENTENCE_SIZE 100

int main (void)

{

char sentence[SENTENCE_SIZE];
char ch;

int i=0;

printf("Enter a message: ");

while((ch=getchar())!='\n')
{
sentence[i++]=ch;
if(i==SENTENCE_SIZE)
break;
};
printf("Reversal is: ");

for(i=strlen(sentence);i>0;i--)

putchar(sentence[i]);

return 0;

} 我调试发现它会自动在我输入的内容后面加一个w,输出就会出错,请问是为什么?

在while(){}的后面加一句sentence[i]='\0';就可以了。。。。。。

0-100,应该是你下标的问题吧。数组下标检查一下,逻辑对不对

感觉i的值应该从长度减一开始,零结束

假设你一共输入了5个字母,strlen(sentence)不包括结尾的空字符,返回值就是5,也就是i被赋值为5,接下来你访问的sentence[i] 其实是数组的第6个字符。从这里就出错了。

#include<stdio.h>
#include<string.h>
#define SENTENCE_SIZE 100
int main()
{
char sentence[SENTENCE_SIZE];
char ch;
int i=0;
printf("Enter a message:");
while ((ch=getchar())!='\n')
{
sentence[i++]=ch;
if (i==SENTENCE_SIZE)
break;
}
sentence[i]='\0';
printf("Reversal is:");
for (i=strlen(sentence);i>=0;i--)
putchar (sentence[i]);
return 0;
}