此代码的问题在于,用户在命令行中输入了一些文本后,它实际上不会打印任何内容。

该代码的目的是接受用户在文件名后通过命令提示符输入的行数。然后,用户将输入一些内容以进行反转。该程序应该颠倒每行的用户输入。

输入示例=大红狗

示例输出=狗红色大

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define SIZE 80

char * reverseWords(char *string);

//argc is the count of cmd arguments.
//each command line argument is of type string
int main(int argc, char *argv[]){

    //initialize local variables
    int i;
    int N;
    char str[SIZE];

    for(i = 1; i <argc; i++)
    {
        //set N equal to the users number in the command line
        N = atoi(argv[i]);
    }

    if(argc != 2){//2 means that something is in the argument.
        printf("ERROR: Please provide an integer greater than or equal to 0");
        exit(1);//exit the program
    }else if(N < 0){//We cant have a negative array size.
        printf("ERROR: Please provide an integer greater than or equal to 0");
        exit(1);//exit the program
    }else{
        for(i = 0; i < N; i++){
            /*
            fgets(pointer to array, max # of chars copied,stdin = input from keyboard)
            */
            fgets(str,SIZE,stdin);

            printf("%s", reverseWords(str)); //<---does not print anything....
        }
    }
    return 0;
}


char * reverseWords(char *line){

    //declare local strings
    char *temp, *word;
    //instantiate index
    int index = 0;
    int word_len = 0;
    /*set index = to size of user input
        do this by checking if the index of line is
        equal to the null-character.
    */
    for(int i = 0; line[i] != '\0';i++)
    {
        index = i;//index = string length of line.
    }

    //check if index is less than 0.
    //if not we decrement the index value.

    for(index; index != -1; index--){
        //checking for individual words or letters
        if(line[index] == ' ' && word_len > 0){
            strncpy(word,line,word_len);
            strcat(temp , (word + ' '));
            word_len = 0;

        }else if(isalnum(line[index])){
            word_len == word_len+1;
        }//end if

    }//end loop

    //copy over the last word after the loop(if any)
    if(word_len > 0){
        strncpy(word,line,word_len);
        strcat(temp,word);
    }//end if
    line = temp;
    return line;
}//end procedure

最佳答案

reverseWords不输出任何内容应该不足为奇。为什么?

char * reverseWords(char *line){
    ...
    char *temp, *word;
    ...
    line = temp;
    return line;
} //end procedure
line指向哪里? (到temp)。 temp在哪里声明? (在reverseWords中)。分配给temp多少存储空间(无-这是未初始化的指针)

此外,当函数reverseWords返回时,与该函数关联的内存会发生什么情况? (它已经被破坏了...),所以即使您做了类似char temp[strlen(line)+1] = "";的操作,reverseWords也会冒险进入未定义行为,因为您返回的指针指向reverseWords堆栈框架中某个位置,该框架在reverseWords返回时被破坏了...

您如何解决这个问题?您有三个选择,(1)将第二个指针传递给具有足够存储空间的第二个数组,例如:
char *revwords (char *rline, char *line)

或(2)动态分配temp的存储空间,以便与temp相关的内存在reverseWords的返回中保留下来,或者

(3)对temp中的reverseWords使用足够大小的数组,并在返回之前用line中的数据覆盖temp。 (例如,使用strcpy而不是分配line = temp;)

尽管动态分配很简单,并且在reverseWords中创建一个单独的数组很好,但您最好将第二个足够大的数组作为参数传递给reverseWords

完全不清楚您在代码中使用argcargv参数是做什么的,下面示例中省略了main的参数。以下是一个简短示例,该示例反转了从stdin读取的每一行中的单词,
#include <stdio.h>
#include <string.h>

#define SIZE 256

char *revwords (char *rline, char *line);

int main (void) {

    char line[SIZE] = "", rline[SIZE] = ""; /* storage for line/rline */

    while (fgets (line, SIZE, stdin)) { /* for each line on stdin */
        printf ("\n line: %s\nrline: %s\n", line, revwords (rline, line));
        *rline = 0; /* set first char in rline to nul-byte */
    }

    return 0;
}

char *revwords (char *rline, char *line)
{
    size_t lnlen = strlen (line);   /* length of line */
    /* pointer, end-pointer, rev-pointer and flag pointer-to-space */
    char *p = line + lnlen - 1, *ep = p, *rp = rline, *p2space = NULL;

    if (!line || !*line) {  /* validate line not NULL and not empty */
        fprintf (stderr, "revwords() error: 'line' empty of null.\n");
        return NULL;
    }

    if (*ep == '\n')    /* if line ends in '\n' -- remove it */
        *ep-- = 0;
    else                /* warn if no '\n' present in line */
        fprintf (stderr, "warning: no POSIX '\\n' found in line.\n");

    for (; ep >= line; ep--) {  /* for each char from end-to-beginning */
        if (*ep == ' ') {               /* is it a space? */
            size_t len = p - ep;        /* get the length of the word */
            strncat (rp, ep + 1, len);  /* concatenate word to rline  */
            if (p == line + lnlen - 1)  /* if first word, append ' '  */
                strcat (rp, " ");
            p = ep;                     /* update p to last ' '  */
            p2space = ep;               /* set flag to valid pointer */
        }
    }
    strncat (rp, line, p - line);       /* handle first/last word */

    if (!p2space) { /* validate line contained ' ', if not return NULL */
        fprintf (stderr, "revwords() error: nothing to reverse.\n");
        return NULL;
    }

    return rline;   /* return pointer to reversed line */
}

注意:如果传递给'\n'line中不存在revwords,则您可能试图读取比SIZE字符更长的行(或者您正在读取文件末尾没有POSIX '\n'的最后一行) ,您需要按要求进行处理。在这里,我只是警告。

示例使用/输出
$ printf "my dog has fleas\nmy cat does too\n" | ./bin/str_rev_words

 line: my dog has fleas
rline: fleas has dog my

 line: my cat does too
rline: too does cat my

仔细看一下,如果您有任何疑问,请与我联系。有许多种方法可以解决此问题,如果它们以合理有效的方式正确处理了逆转,则没有比另一对的权利。随便你吧。

如果您喜欢使用字符串库函数而不是指针算术,则可以始终执行以下操作:
char *revwords (char *rline, char *line)
{
    /* length, pointer, end-pointer, pointer-to-space, copy of line */
    size_t len = strlen (line);
    char *p = NULL, *p2space = NULL, copy[len+1];

    if (!line || !*line) {  /* validate line not NULL and not empty */
        fprintf (stderr, "revwords() error: 'line' empty of null.\n");
        return NULL;
    }

    if (line[len-1] == '\n')    /* remove trailing newline */
        line[--len] = 0;
    else                /* warn if no '\n' present in line */
        fprintf (stderr, "warning: no POSIX '\\n' found in line.\n");

    strncpy (copy, line, len + 1);  /* copy line to 'copy' */

    /* for each ' ' from end-to-beginning */
    while ((p = strrchr (copy, ' '))) {
        strcat (rline, p + 1);          /* append word to rline */
        strcat (rline, " ");            /* followed by a space  */
        p2space = p;                    /* set p2space to p     */
        *p2space = 0;                   /* nul-terminate copy at p */
    }

    if (p2space) {              /* validate space found in line */
        *p2space = 0;           /* nul-terminate at space       */
        strcat (rline, copy);   /* concatenate first/last word  */
    }
    else {                      /* no ' ' in line, return NULL  */
        fprintf (stderr, "revwords() error: nothing to reverse.\n");
        return NULL;
    }

    return rline;   /* return pointer to reversed line */
}

注意:尽管不是错误,但C的标准编码样式避免使用caMelCaseMixedCase变量或函数名称来支持所有小写字母,同时保留了大写字母名称以供宏和常量使用。将caMelCaseMixedCase保留为Java或C++。 (这是样式,所以这是您的选择,但它确实会在第一印象中说明您的代码)

10-06 01:40