c - C 中的 tolower 函数不允许我转换字符串

标签 c

考试的课文说

The program should execute in a case-insensitive way, e.g. "How" and "hoW" are the same word

所以我创建了一个字符,使用 atoi 将其传递给一个值,然后我尝试将其所有内容转换为小写。

示例:

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

#define STR_LEN 20 

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

    if(argc != 3) {
        fprintf(stderr, "Incorrect number of arguments.\n");
        exit(EXIT_FAILURE);
    }

    char word1[STR_LEN +1];
    strcpy(word1, argv[1]);

    int i;
    for(i=0;i<strlen(word1);i++){
    word1 = tolower(word1[i]);
    }

    char word2[STR_LEN +1];
    strcpy(word2, argv[2]);

    FILE *fin;
    fin = fopen("MyTEXTFile.TXT", "r");
    if(fin == NULL) {
        fprintf(stderr, "Can't open the file.\n");
        exit(EXIT_FAILURE);
    }

    char w1[STR_LEN +1] = "";
    char w2[STR_LEN +1];
    int found = 0;

    while(fscanf(fin, "%s", w2) != EOF) {
        printf("DEBUG: Checking \"%s\" \"%s\"\n", w1, w2);

        if(strcmp(w1, word1)==0 && strcmp(w2, word2)==0) {
            ++found;
        }
        if(strcmp(w1, word2)==0 && strcmp(w2, word1)==0) {
            ++found;
        }

        strcpy(w1, w2);
    }
    fclose(fin);

    if(found > 0) {
        printf("The words \"%s\" and \"%s\" appear consecutively in the text %d times", word1, word2, found);
    } else {
        printf("The words \"%s\" and \"%s\" never appear consecutively in the text", word1, word2);
    }

    return EXIT_SUCCESS;
}

为什么程序在这里给我报错:

 int i;
 for(i=0;i<strlen(word1);i++){
   word1 = tolower(word1[i]);
 }

将它们全部转换为小写的正确做法是什么?

最佳答案

更改为:

int i;
for(i=0;i<strlen(word1);i++){
    word1[i] = tolower(word1[i]);
}

在你的代码中,你将word1的字符赋给字符串指针,非常糟糕

关于c - C 中的 tolower 函数不允许我转换字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32170385/

相关文章:

c - 如何在 Windows 中退出阻塞的 accept() 调用?

c - 以宽字符作为索引的全局 C 数组

C:如何将一串整数转换为实际的整数并将它们存储在数组中?

c++ - 当我复制 pthread_rwlock_t 时会发生什么?

c - 结构数组崩溃程序 C

c - 有没有办法在行为不当的指定初始化器时得到警告?

c - 定点表示的符号

c# - 什么是 C snprintf() 的 C# 模拟?

c - 通过代理从网站获取数据

c++ - 为什么在 Win32 中使用 `GetAsyncKeyState()` 时我的热键会出错?