0

所以基本上:

#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 character
    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;
}

通过运行这个程序并输入字符串....假设“飞镖”将反转数组中的字符串,该字符串将具有元素 s2[0]= '\012' =10(decimal), ...strad.. ., s2[7]='\0'。strrev 的行为是否正常?

4

3 回答 3

4

fgets将换行符存储在字符串中。所以当你strrev, \n(linefeed) 将是第一个元素。

fgets()函数应将流中的字节读取到 s 指向的数组中,直到读取 n-1 个字节,或者 读取 a 并将其传输到 s

编辑

刚刚在 Visual Studio 上测试过:

char a[] = "abcd\n";
strrev(a);

printf("%d\n", a[0]); /* 10 */
于 2011-07-24T16:31:59.483 回答
2

strrev反转给定字符串中字符的顺序。结束空字符\0保持不变。

fgets在这种情况下存储换行符。

于 2011-07-24T16:30:51.657 回答
1

fgets将换行符存储在 char 数组中作为最后一个字符。strrev 将保留此字符以及以空字符结尾的字符(例如 \010)。ASCII 10 是换行符。该字符串是空终止的(\0),所以strrev只是采用空终止的char数组并将其反转。如果您不想要空终止字符,则将其删除。strrev反转给定字符串中字符的顺序。结束空字符 (\0) 保持不变。

于 2011-07-24T16:32:58.790 回答