程序返回字符而不是字符串

时间:2016-12-01 17:03:50

标签: c loops for-loop

我的程序有问题。它假设根据所选择的开关返回字符串,但它只返回所有时间" D"。我不知道出了什么问题。我也可能会在while循环中弄乱一些东西。

  

的main.c

#include <stdlib.h>
#include <stdio.h>
#include "WordTools.h"

int main(int argc, char *argv[]) {
    char line[200];
    char temp[200];
    int i = 0;

    printf("Enter a string: \n");
    while(fgets(line, sizeof(line),stdin)){
        temp[i] = strdup(line);
        i++;
    }

    switch (argc > 1 && argv[1][1]) {
    case 'l':
    case 'L':
        printf("%c", makeLower(line));
        break;
    case 'u':
    case 'U':
        printf("%c", makeUpper(line));
        break;
    case 'c':
    case 'C':
        printf("%c", makeChange(line));
        break;
    case 'n':
    case 'N':
        printf("%c", makeName(line));
        break;
    default:
        printf("%c", makeUpper(line));
        break;
    }
    return 0;
}
  

worldtools.c

#include <stdio.h>
#include <ctype.h>
#include "WordTools.h"

char makeLower(char *s) {
    int i;
    for(i = 0; s[i] != '\0'; i++){
        s[i] = tolower(s[i]);
    }
    return s;
}

char makeUpper(char *s) {
    int i;
    for(i = 0; s[i] != '\0'; i++){
        s[i] = toupper(s[i]);
    }
    return s;
}

char makeChange(char *s) {
    int i;
    for(i = 0; s[i] != '\0'; i++){
        if ((s[i] >= 65) && (s[i] <= 90)) s[i] = tolower(s[i]);
        else if ((s[i] >= 97) && (s[i] <= 122)) s[i] = toupper(s[i]);
    }
    return s;
}

char makeName(char *s) {
    int i;
    s[0]=toupper(s[0]);
    for(i = 1; s[i] != '\0'; i++){
        s[i] = tolower(s[i]);
    }
    return s;
}

1 个答案:

答案 0 :(得分:1)

<强>更新

检查以下代码:

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

char makeLower(char *s) {
    int i;
    for(i = 0; s[i] != '\0'; i++){
        s[i] = tolower(s[i]);
    } // Big mistake: there is no point returning s, because we are operating on the address of s, meaning, whatever changes you make, it stays!
}

int main(int argc, char *argv[]) {
    char line[200];

    if (argc > 1) {  
      strcat(line, argv[1]); // this is just a quick way to test your code. You need to do something, cleaner. But, basically, it takes the arguments from your terminal and saves it as line.
      printf("%s\n", line);
    }
    else return 0; // exit code

    makeLower(line); // here we make changes to line, the line variable is permanently changed.
    printf("%s\n", line);


    return 0;
}

我正在使用ubuntu。所以要在终端中运行这段代码,我写道:

aykjas@asdk:~/Desktop$ gcc main.c -o main
aykjas@asdk:~/Desktop$ ./main HELLO

如您所见,输出更改为更低:

HELLO
hello

我希望这会有所帮助。