簡體   English   中英

我只是想弄清楚為什么不打印反轉的字符串。 我從“C 編程語言”中閱讀了這段代碼

[英]I am just trying to figure out why the reversed string isn't printing. I read this code from, "The C Programing Language"

#include <string.h> 
/* reverse: reverse string s in place */
void reverse(char s[])
{
    int c, i, j;
    //defining some variables
    for (i = 0, j = strlen(s) - 1; i < j; i++, j--) {
    // j becomes the length of string s's characters which will occur for all the words

        c = s[i];
        #
        s[i] = s[j];

        s[j] = c;
        //C should be the reversed string s
        printf(c);
    }
}

#老實說,我不確定某些代碼在做什么。 #我的一個主要問題是代碼字符串的用戶輸入在哪里。

如評論中所述,“printf”語句將引發編譯器警告,並且不會產生任何類型的所需 output。 否則,在 function 中發生的字符交換會執行預期的操作,即反轉輸入字符串的字符位置。 以下代碼片段說明了如何使用它。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/* reverse: reverse string s in place */
void reverse(char s[])
{
    int c, i, j;
    //defining some variables
    for (i = 0, j = strlen(s) - 1; i < j; i++, j--) {
    // j becomes the length of string s's characters which will occur for all the words

        c = s[i];
        #
        s[i] = s[j];

        s[j] = c;
        //C should be the reversed string s
        //printf(c);
    }
}

int main(int argv, char *argc[])
{
    if (argv < 2)
    {
        printf("Usage: \"Reversi \"input string\"\"\n");
        return 0;
    }

    char sample[256];

    strcpy(sample, argc[1]);

    printf("Initial string: %s\n", sample);

    reverse(sample);

    printf("Reversed string: %s\n", sample);

    return 0;
}

“反向” function 將在程序的其他地方調用。 在這種情況下,一旦從輸入參數中保護了字符數組值,就會從“主”function 調用它。 以下是來自測試的 output 示例。

@Una:~/C_Programs/Console/Reversi/bin/Release$ ./Reversi "John Doe"
Initial string: John Doe
Reversed string: eoD nhoJ

如前所述,這只是將字符數組引入“反向”function 的眾多可能性之一。

試試看。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM