Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

invalid conversion from ‘const char*’ to ‘char’

I am trying to replace a certain character in a string with a space using the following code line:

str[i] = " ";

How can realize this without getting the error in the title of the question?

like image 427
Debugger Avatar asked Nov 10 '11 19:11

Debugger


People also ask

What is const char*?

const char* is a mutable pointer to an immutable character/string. You cannot change the contents of the location(s) this pointer points to. Also, compilers are required to give error messages when you try to do so. For the same reason, conversion from const char * to char* is deprecated.


2 Answers

use single quotes

str[ i ] = ' ';

In C++, the token " " is a string literal which represents an array of two characters: the value of a space in the character set (eg, the value 32 in ascii) and a zero. On the other hand, the token ' ' represents a single character with the value of a space (usually 32). Note that in C, the token ' ' represents an integer with the value of a space. (In C, sizeof ' ' == sizeof(int), while in C++, sizeof ' ' == sizeof(char) == 1.)

like image 61
William Pursell Avatar answered Oct 24 '22 09:10

William Pursell


Single char literals are obtained with single quotes:

str[i] = ' ';

A literal with double-quotes is a full string literal (a null-terminated array of char), but you're only replacing a single char.

like image 38
Lightness Races in Orbit Avatar answered Oct 24 '22 08:10

Lightness Races in Orbit