This question already has answers here:
What do single quotes do in C++ when used on multiple characters?
(5 answers)
Closed 6 years ago.
During learning about C++ by reading a book I have seen this (for me) strange line of code.
char ch('AB'); // Or char ch = 'AB';
It is strange for me because I don't get that you can assign to a char multiple "letters" without getting any exception.
cout << "Characters in ch: " << ch << endl; // Output B
Why does this work? And how is it working internally? Is it only saving the last character and ignoring the other ones?
It's called a multicharacter literal which are completely valid C++:
Multicharacter literal, e.g. 'AB', has type int and implementation-defined value.
[...]
Many implementations of multicharacter literals use the values of each char in the literal to initialize successive bytes of the resulting integer, in big-endian order, e.g. the value of '\1\2\3\4' is 0x01020304.
It is strange for me because I don't get that you can assign to a char multiple "letters" without getting any exception.
You should see it as a type conversion (demo):
#include <iostream>
using namespace std;
int main()
{
{
int i = 'abcd';
char c = i; // cast form int to char -> c == 'd'
cout << c; // prints 'd'
}
{
char c = 'abcd'; // cast form int to char -> c == 'd'
cout << c; // prints 'd'
}
return 0;
}
The order in which the characters are stored in int is not specified by standard. However, a well designed compiler will consider endianness when storing a multi-character constant: GCC and VisualC behaves the same way.
Related
In Difference between char and int when declaring character, the accepted answer says that the difference is the size in bits. Although, MicroVirus answer says:
it plays the role of a character in a string, certainly historically. When seen like this, the value of a char maps to a specified character, for instance via the ASCII encoding, but it can also be used with multi-byte encodings (one or more chars together map to one character).
Based on those answers: In the code below, why is the output not the same (since it's just a difference in bits)? What is the mechanism that makes each type print a different "character"?
#include <iostream>
int main() {
int a = 65;
char b = 65;
std::cout << a << std::endl;
std::cout << b << std::endl;
//output :
//65
//A
}
A char may be treated as containing a numeric value and when a char is treated such it indeed differs from an int by its size -- it is smaller, typically a byte.
However, int and char are still different types and since C++ is a statically typed language, types matter. A variable's type can affect the behavior of programs, not just a variable's value. In the case in your question the two variables are printed differently because the operator << is overloaded; it treats int and char differently.
This question already has answers here:
cout << with char* argument prints string, not pointer value
(6 answers)
Closed 2 years ago.
I have written a simple C++ code, and its working fine. But I don't know how it is working. I am just replacing "l" with "r" using myfun().
The return type of myfun() is char*. If I am returning &(str[0]), that is, only the address of the first element of the array, then why is it printing the complete string "herloworld"? Please explain what return &(str[0]); is doing.
#include <iostream>
using namespace std;
char* myfun(char str[])
{
str[2] = 'r';
return &(str[0]);
}
int main()
{
char str[] = "helloworld";
char* word;
word = myfun(str);
cout << word;
}
The operator << is overloaded for the type char * such a way that it expects that the used pointer of the type char * points to the first character of a string.
So the operator outputs all characters of the passed string until the zero character '\0' is encountered.
Also pay attention to that arrays used in expressions with rare exceptions are converted to pointers to their first elements.
So this call
word = myfun(str);
is equivalent to
word = myfun( &str[0]);
On the other hand, a function parameter having an array type is implicitly adjusted to pointer to the element type.
So this function declaration
char* myfun(char str[]);
is equivalent to the following declaration
char* myfun(char *str);
The both declarations declare the same one function.
And within the function instead of this return statement
return &(str[0]);
you could write
return str;
Correspondingly in main you could write
cout << myfun(str);
without declaring and using the intermediate pointer word.
I am writing a c++ program, in which I need to store the value of a special ASCII character(eg:-'β ','β³','β²',etc.) in a character variable like :
#include <iostream>
using namespace std;
int main(void)
{
char a = 'β ';//here...
cout << a;
return 0;
}
...and it throws errors saying
warning: multi-character character constant [-Wmultichar]
and
warning: overflow in implicit constant conversion [-Woverflow]
Is there any way to do this ???
You have to use the wide character datatype, as it can store ASCII as well as non-ASCII characters in C++, which is represented by wchar_t.
#include<iostream>
using namespace std;
int main()
{
wchar_t a = L'π';
wcout << a;
return 0;
}
As shown above, the smiley character gets stored in a. Since it involves wide character(s), to display it to console, I have to use std::wcout. Similarly, std::wcin is the wide character alternative for std::cin and std::wstring for std::string.
The L prefix is used to represent wide characters and wide strings. Here, it is used to tell the compiler that π is a wide character.
This question already has answers here:
What does string + int perform in C?
(3 answers)
Closed 5 years ago.
Is it possible to create array of char from different data types merging it into one char array. char array[32] = "matrix"+a+b+".txt"; E.g:
int main(){
int a = 10;
int b = 10;
char array[32] = "matrix"+a+b+".txt";
return 0;
}
I have tried different ways. But it didn't helped. Thank you!
For C, use snprintf():
int a = 10;
int b = 10;
char array[32];
snprintf(array, sizeof(array), "matrix%d%d.txt", a, b);
For C++, use strings instead of character arrays; you can concatenate strings easily since they overload the + operator:
int a = 10;
int b = 10;
std::string str{std::string{"matrix"} + std::to_string(a) + std::to_string(b) + ".txt"};
I think you should firstly understand how a C-string works... a C-String is always an array of chars... but an array of char is not always a C-String.
The "definition" (not a formal definition, but something close to it) is that a C-String contains a sequence of bytes that will represent a string (characters) and the end of the string will be marked with a null-byte (0)
This is a C-String:
char myString[4] = { 'a', 'b', 'c', 0 };
This is NOT a C-String:
char myBuffer[3] = { 'a', 'b', 'c' };
Checking your example... trying to make "matrix"+a+b+".txt" shows that you are actually looking for construct a C-String with different types.
--
So, in order to mix different types of data in order to build a string we have several options...
In C: use snprintf()
In C++: use std:string or std::ostringstream
There are more options for both, but these above are very common.
The std::string in C++ is NOT a C-String... but can be converted to one with the function .c_str().
This question already has an answer here:
C++ warning: deprecated conversion from string constant to βchar*β [-Wwrite-strings]
(1 answer)
Closed 8 years ago.
I use the cmd to compile with a .bat and g++.exe. Can someone tell me what I did wrong? I am using it to practice as I follow a tutorial on strings and arrays. Please keep in mind that I am still learning.
main.cpp: In function 'int main()':
main.cpp:6:12: warning: deprecated conversion from string constant to 'char*' [-
Wwrite-strings]
main.cpp:10:12: warning: deprecated conversion from string constant to 'char*' [
-Wwrite-strings]
main.cpp:11:12: warning: deprecated conversion from string constant to 'char*' [
-Wwrite-strings]
Press any key to continue . . .
My Code:
using namespace std;
#include <iostream>
int main() {
//Asterisk to make the variable an array. Takes 8 bytes of memory (8 characters including spaces).
char *a = "hi there";
//Inside square brackets is the number of bytes of memory to use. More consumtion of resources
char b[500]="hi there";
//For a new line, type \n. For a tab, type \t.
char *c = "Hi There\nFriends!";
char *d = "\t\tHi There Friends!";
//endl will end the line.
cout << a;
cout << b << endl;
cout << c << endl;
cout << d << endl;
}
Strings between double quotes are string literals. They are arrays of char which are not to be modified (attempting to modify them invokes undefined behavior). That's why you should declare a pointer pointing to a string literal as const char * - this way, if some code erroneously tries to write/modify a character in the literal, the compiler will have a chance to catch this error.