nb023
nb023

Reputation: 35

How to fix "warning: multi-character character constant [-Wmultichar]"

So basically the function searches a file for the '\t' (tab) character and when it finds it, its suppose to replace it with a '^I'

Problem is c = '^I' produces a warning warning: multi-character character constant [-Wmultichar]. The other problem is only the I shows up not the ^.

If I change it to c = "^I" I get this warning "Warning: Assignment makes integer from pointer without a cast". This way also puts "\\" instead of ^I

How can I solve this? Is there a better way to do it?

if ((fileContents = fopen("fileContents.txt", "r")) == 0) 
{
    perror("fopen");
    return 1; 
}

while ((c = fgetc(fileContents)) != EOF)
{

    if (c == '\t')
    {
        c = '^I';
    }
    putchar(c); 
}

Upvotes: 0

Views: 33901

Answers (3)

Ryan Haining
Ryan Haining

Reputation: 36882

A char can only be a single character. '^I' is two. In your case you'll want to if/else on the character, printing the string using a normal printf

if (c == '\t') {
    printf("^I");
} else {
    putchar(c);
}

Upvotes: 1

Imobilis
Imobilis

Reputation: 1489

You can not put two characters in a character literal. '^I' here, there are two characters - ^ and I. This is responsible for the warning:

multi-character character constant

not sure what are you trying to achieve here, but in C you can only put single ASCII character or character escape sequence in single quotes. the ^ is system-specific ANSI escape code I think for terminal color, supported by DOS and UNIX. You can use it in a string as far as you have it declared somewhere with static or dynamic allocation or just use the printf function to print it out to the standard output stream: printf("^I ^O test");


As for the implicit declaration. I do assume that c is declared as an integer or some other sort of arithmetic-type. You can not assign a string literal to it, not in any manner. You can do that with the functions strcpy sprintf strncpy etc. In that case, c must have been statically or dynamically allocated. To avoid false implicit declaration make sure it is with the type of char* so an area of chars, where the last one is the null-terminating character. If you want to assign a string literal to a char* you will store it in read-only memory area.

char *string;

string = "^I";

printf(string);

You can turn off warnings with the pragma warning directive. Don't do that. Warnings are there for a reason.

Upvotes: 1

o11c
o11c

Reputation: 16136

'^I' is, quite obviously, two characters. You can't use putchar with multiple characters, and as gcc warns you, multi-char constants are not something you want to use.

Instead, make sure you use a string. Try something like:

const char *replacement = NULL;
if (c == '\t') replacement = "^I";

if (replacement) fputs(replacement, stdout);
else putchar(c);

Upvotes: 0

Related Questions