'c++ Char input takes the first letter but char casting doesnt
I dont understand the datatype char very well. Its because of that example:
char test;
cin >> test;
cout << test;
If i input now more than one char, the program only prints the first letter.
char test = (char)"Hello";
But If I cast a string like hello to a char, the program doesnt take the first letter.
void menu() {
char mode = ' ';
cout << "Gebe einen Modus an. 1 Addition, 2 Subtraktion, 3 Multiplikation, 4 Division: ";
cin >> mode;
switch (mode) {
case '1':
addition();
break;
case '2':
subtraktion();
break;
case '3':
multiplikation();
break;
case '4':
division();
break;
default:
cout << "Ungueltige Eingabe, versuch es nochmal\n";
menu();
break;
}
}
Also in this example, If I give the program as an input more than one letter, the default condition will be executed so many times, as the length of the input.
I dont understand those three examples well, could anybody explain me everything in easy from the start=? That would be really nice! Thanks in advance
Solution 1:[1]
You're misunderstanding what a char is and mistaken it for a string which is an array of char with a terminating null character.
The char data type is used to store a single character.
Therefore, you will only get 1 character from the input. In order to get a stream of multiple characters you should use the datatype char* or std::string.
Solution 2:[2]
- since you expect a type of char (which is one character, so one letter only) from stdin you will only get the first character you input.
- you can not cast a string literal "Hello" (which is a pointer-type: const char*) to char like that. You would have to do the following to only get the first character:
char test = *("Hello");
Learn more about pointers and references here: https://www.cplusplus.com/doc/tutorial/pointers/
Solution 3:[3]
char is for only one character. If you want to take multiple characters, you have to use array of char or string.
char test = (char)"Hello";
Please use this:
char test[6] = "Hello";
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Wahalez |
| Solution 2 | |
| Solution 3 |
