Ismail Khater
Ismail Khater

Reputation: 3

The function tolower in C does not allow me to convert a string

The text of an exam says

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

so I created a char, passed it using atoi to a value, then I tried to convert all its contents to lowercase.

Example:

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

Why does the program give me an error here:

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

and what should be the right thing to do to convert all of them to the lowercase?

Upvotes: 0

Views: 378

Answers (2)

eyalm
eyalm

Reputation: 3366

See tolower man page. The function converts only one char at a time. You have to run over all the string and convert one char using word1[i]. If you want only a case insensitive comparison, you can use strcasecmp

int i;

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

Upvotes: 0

gengisdave
gengisdave

Reputation: 2050

Change to :

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

in your code, you assign word1's characters to the string pointer, very bad

Upvotes: 2

Related Questions