strrev function inserts a line feed character in the first element of a string array
So basically:
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <string.h>
int main(void){
//test strrev
char s[50];
char s2[50];
char *ps;
int i=0;
printf("String to reverse: ");
fgets(s,50,stdin);
ps=strrev(s);
strcpy(s2,ps); //copy contents to a string array
//i did the copy because using printf("%s", ps); did the same thing
printf("Reversed string: %s\n", s2); //PECULIAR, s2 enters line feed char in s2[0]
//test loop to determine the inserted ch开发者_如何转开发aracter
while(1){
if(s2[i]==10) {printf("is 10,%d", i); break;}; //the proof of LF
if(s2[i]==12) {printf("is 12"); break;};
if(s2[i]==13) {printf("is 13"); break;};
if(s2[i]==15) {printf("is 15"); break;};
i++;
}
for(i=0;i<50;i++){ //determine where the characters are positioned
printf("%c: %d\n", s2[i], s2[i]);
if(s2[i]=='\0') break;
}
system("PAUSE");
return 0;
}
By running this program and entering the string....let's say "darts" will reverse the string in the array that will have the elements s2[0]='\012'=10(decimal), ...strad..., s2[7]='\0'. Is it normal for strrev to behave as such?
fgets
stores the newline in the string. So when you strrev
, \n
(linefeed) will be the first element.
The
fgets()
function shall read bytes from stream into the array pointed to by s, until n-1 bytes are read, or a is read and transferred to s.
EDIT
Just tested it on Visual Studio:
char a[] = "abcd\n";
strrev(a);
printf("%d\n", a[0]); /* 10 */
strrev
reverses the order of the characters in the given string. The ending null character \0
remains in place.
fgets
is storing the newline in this case.
fgets
stores the newline character in the char array as the last character. strrev will keep this character along with the null-terminated character (e.g. \010). ASCII 10 is newline. The string is null terminated (\0
), so strrev
is just taking the null-terminated char
array and reversing it. If you don't want the null terminated character, then remove it. strrev
reverses the order of the characters in the given string. The ending null character (\0) remains in place.
精彩评论