About the Program
The program takes a number the user entered and outputs that number doubled. I created two functions, one that gathers the number (getnumber), and another that doubles it (doublenumber). The program does work properly; however, the output is not completely accurate.
The Problem
The output is only right partially. I.e the user enters 50, the value is doubled and the output should be 100. Instead, the value outputs as 100114. Only the first few numbers seem to be what I want.
Source Code:
#include <iostream>
void doublenumber(int&);
void getnumber(int&);
int main() {
int value;
getnumber(value);
doublenumber(value);
std::cin.get();
std::cin.get();
return 0;
}
void doublenumber(int &refvar) {
refvar*= 2;
std::cout << "\nThe value you entered doubled is: " << refvar << '.\n';
}
void getnumber(int &userNum) {
std::cout << "\nEnter a number to double: ";
std::cin >> userNum;
}
std::cout << "\nThe value you entered doubled is: " << refvar << '.\n';
^^^^^
|
multicharacter literal
It's a multicharacter literal, and has a type of int.
C++11 §2.13.2 Character literals
A character literal is one or more characters enclosed in single quotes, as in ’x’, optionally preceded by the letter L, as in L’x’. A character literal that does not begin with L is an ordinary character literal, also referred to as a narrow-character literal. An ordinary character literal that contains a single c-char has type char, with value equal to the numerical value of the encoding of the c-char in the execution character set. An ordinary character literal that contains more than one c-char is a multicharacter literal. A multicharacter literal has type int and implementation-defined value.
Check out this post: Why does this code with '1234' compile in C++?.
I have answered my own question after carefully looking over the code. Ugh! A very simple mistake at:
std::cout << "\nThe value you entered doubled is: " << refvar << '.\n';
The "'.\n'" should be: ".\n";" instead. Could someone tell me why this produced this output though?
Related
I don't know the cause of errors compiling using g ++. Am I using obsolete classes?
My MWE:
#include <iostream>
using namespace std;
int main()
{
system("cls");
cout << "\n\n";
cout <<"\n\t\xDC\xDC\xDB\xDB\xDB\xDB\xDC\xDC";
cout <<"\n\t\xDF0\xDF\xDF\xDF\xDF0\xDF";
cout <<"\n\n";
cout <<"\n\t\xDC\xDC\xDB\xDB\xDB\xDB\xDB\xDB\xDB";
cout <<"\n\t\xDF0\xDF\xDF\xDF\xDF\xDF00\xDF";
cout << "\n\n";
cout << endl;
system("PAUSE");
return 0;
}
**
Result at compiling:
$ g++ 14.cpp
14.cpp: In function ‘int main()’:
14.cpp:11:9: warning: hex escape sequence out of range
11 | cout <<"\n\t\xDF0\xDF\xDF\xDF\xDF0\xDF";
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
14.cpp:11:9: warning: hex escape sequence out of range
14.cpp:16:9: warning: hex escape sequence out of range
16 | cout <<"\n\t\xDF0\xDF\xDF\xDF\xDF\xDF00\xDF";
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
14.cpp:16:9: warning: hex escape sequence out of range
$ ./a.out
sh: cls: command not found
A hex escape sequence supposed to be formatted as \Xnn. It complains because you provide more than 2 hex values as in \xDF0 and \xDF00.
---EDIT---
For completeness, quote from cppreference:
Hexadecimal escape sequences have no length limit and terminate at the
first character that is not a valid hexadecimal digit. If the value
represented by a single hexadecimal escape sequence does not fit the
range of values represented by the character type used in this string
literal (char, char16_t, char32_t, or wchar_t), the result is
unspecified.
And to stop escaping hex characters, another quote from cppreference:
If a valid hex digit follows a hex escape in a string literal, it would fail to compile as an invalid escape sequence. String concatenation can be used as a workaround:
//const char* p = "\xfff"; // error: hex escape sequence out of range
const char* p = "\xff""f"; // OK: the literal is const char[3] holding {'\xff','f','\0'}
I wrote the following code
#include <iostream>
#define circleArea(r) (3.1415*r*r)
int main() {
std::cout << "Hello, World!" << std::endl;
std::cout << circleArea('10') << std::endl;
std::cout << 3.1415*'10'*'10' << std::endl;
std::cout << 3.1415*10*10 << std::endl;
return 0;
}
The output was the following
Hello, World!
4.98111e+08
4.98111e+08
314.15
The doubt i have is why is 3.1415 * '10'*'10' value 4.98111e+08. i thought when i multiply a string by a number, number will be converted to a string yielding a string.Am i missing something here?
EDIT: Rephrasing question based on comments, i understood that single quotes and double are not same. So, '1' represents a single character. But, what does '10' represent
'10' is a multicharacter literal; note well the use of single quotation marks. It has a type int, and its value is implementation defined. Cf. "10" which is a literal of type const char[3], with the final element of that array set to NUL.
Typically its value is '1' * 256 + '0', which in ASCII (a common encoding supported by C++) is 49 * 256 + 48 which is 12592.
int main()
{
char hmm[1000];
cin.getline(hmm, 1000);
cout << hmm << endl; //this was to test if I could assign my input to the array properly
for (int sayac = 0; hmm[sayac] != '#'; sayac++) {
if (!isdigit(hmm[sayac])) {
if (islower(hmm[sayac]))
cout << toupper(hmm[sayac]);
else if (isupper(hmm[sayac]))
cout << tolower(hmm[sayac]);
else
cout << hmm[sayac];
}
}
"Write a program that reads keyboard input to the # symbol and that echoes the input
except for digits, converting each uppercase character to lowercase, and vice versa.
(Don’t forget the cctype family.) "
I'm doing this exercise from the primer book. But when I run it, it returns the ascii order of the char, not the uppercase/lowercase version of the character. Couldn't figure out the problem. Can someone tell my why please?
(I may have other problems about the exercise, please don't correct them if I have. I want to fix it on my own (except the problem I explained), but I can't check the other ones as I have this problem.
When writing
std::cout << toupper('a');
the following happen:
int toupper(int ch) is called, and returns an integer whose value is 'A' (0x41).
std::basic_ostream::operator<<(std::cout, 0x41) is called, that is the int (2) overload since an int was provided.
Overall, it prints "65".
As a solution, you can cast back your upper case to a char:
std::cout << static_cast<char>(toupper('a'));
It's a question of representation. There is no difference between a character and that character's numeric value. It's all in how you choose to display it. For example, the character 'a' is just a constant with a value equal to the character's numeric value.
The problem you are having is that std::toupper and std::tolower return an int rather than a char. One reason for that is that they handle EOF values, which are not necessarily representable by char. As a consequence, std::cout see you are trying to print an int and not a char. The standard behavior for streaming an int is to print the number. The solution is then to cast your result to char to force the value to be interpreted as a character. You can use something like std::cout << static_cast<char>(std::toupper(hmm[sayac]));.
Try the following :
#include <cctype>
#include <iostream>
int main()
{
char hmm[1000];
std::cin.getline(hmm, 1000);
std::cout << hmm << std::endl; //this was to test if I could assign my input to the array properly
for (int sayac = 0; hmm[sayac] != '#'; sayac++) {
if (!std::isdigit(hmm[sayac])) {
if (std::islower(hmm[sayac]))
std::cout << static_cast<char>(std::toupper(hmm[sayac]));
else if (isupper(hmm[sayac]))
std::cout << static_cast<char>(std::tolower(hmm[sayac]));
else
std::cout << hmm[sayac];
}
}
}
You should also consider using an std::string instead of an array of char of arbitrary length. Also, take note that you have undefined behavior if the input string does not contain #.
I am doing some coding for a beginner C++ class I am taking. In the class, we have to take code submitted by another student and fix a bug they created. The code is as follows:
#include <iostream>
using namespace std;
int countChars(char *, char); // Function prototype
int main()
{
const int SIZE = 51; // Array size
char userString[SIZE]; // To hold a string
char letter; // The character to count
// Get a string from the user.
cout << "Enter a string (up to 50 characters): ";
cin.getline(userString, SIZE);
// Get a character to count occurrences of within the string.
cout << "Enter a character and I will tell you how many\n";
cout << "times it appears in the string: ";
cin >> letter;
// Display the number of times the character appears.
cout << letter << " appears ";
cout << countChars(userString, letter) << " times.\n";
return 0;
}
int countChars(char *strPtr, char ch)
{
int times = 0; // Number of times ch appears in the string
// Step through the string counting occurrences of ch.
while (*strPtr != '\0')// ***** There was a one placed inside the null operator, however, this is not a syntax error, but rather just incorrect.
{
if (*strPtr == ch) // If the current character equals ch...
times++; // ... increment the counter
strPtr++; // Go to the next char in the string.
}
return times;
}
The student changed the function such that it had the null terminator as \10, which did not cause a compile nor run time error. After playing with it, I found that it could also be \1 and still work. How is this possible. I am a complete noob, so I apologize if this is a stupid question, but I assumed that this was a boolean operator and 1 was true and 0 was false. The question is why will \10 and \1 work as the null terminator. Thank you in advance!
'\0' means "the character having the integer representation 0." Similarly, '\10' means "the character having the integer representation 10." That's why it's not a compilation error--only a logical error.
The "\0" is the only one to be called a NULL terminator. Even though "\1" or "10" or even "\103" work, only "\0" is referred to as the NULL terminator. I'll explain why.
In "\0" the 0 refers to the OCT value in the ascii table (see picture below). In the ascii table, there is no character whose OCT value is 0, therefore, if we try to use 0, it is referred to as a NULL terminator, because it points to the ground and nothing meaningful or useful.
Now, why does "\10" and "\1" work? Because these refer to OCT values 1 and 10, which can be mapped to a character on the ascii table, notably Start of Heading and Baskspace. Similarily, if you pick a OCT value that points to a letter, punctuation mark or a number, like for example, "\102" points to B, it will output B.
If you try an invalid number, like "\8", then it will simply output 8 on the screen, since it does not refer to a valid character on the ascii table.
See this code, it summarizes all the different types of pointers:
#include <iostream>
using namespace std;
int main(void)
{
cout << "\0" << endl; // This is NULL; points to the ground
cout << "\8"; << endl; // Invalid OCT value; outputs invalid number input with only a warning. No compilation error. Here, 8 will be output
cout << "\102"; // Valid; points to B. Any valid OCT value will point to a character, except NULL.
}
EDIT: After doing some research, I noticed that the correct way to use the escape sequences is indeed with only 3 numbers at minimum. Therefore, even the NULL terminator should technically be written as "\000", following the octal method. However, the compilers can apparently tell which octal value is being referred to even if it is not written in octal format. In other words, "\1" is interpreted by the compiler as "\001". Just some extra information.
I found this information at: C++ Character Literals
Why I cannot initialize string with "\x"
string s = "\x"
It would be useful if I could later write:
int grade = 0;
while (cin >> grade)
if (grade < 60)
cout << "Your grade letter is F!";
else {
x = 50 - grade/10;
s = s + static_cast<string>(x);
cout << "Your grade letter is " << s << endl;
}
I prefer answer, that uses escape sequences computation for setting grade letter.
Because the syntax forbids it. The \x sequence in a string literal is a prefix that means "here comes the hexadecimal code for a character", but you're trying to omit the code part. That means it's not possible to parse the literal and figure out which character to put in the string.
Note that this is a compile-time thing, it has to be possible to compute the sequence of characters represented by a string literal, by just looking at the literal itself.
You misunderstand the way the escape sequences are processed. They are computed at compile-time, not at run time. On other words, when you write
"\x48"
it does not become a string of four characters at runtime; compiler converts it to a single-character string before the program is run.
You also misunderstand static_cast<...>: if x is not a std::string, static-casting it to string will result in an error; if it is a std::string, static-casting will have no effect.
You can create a single-character string at runtime and put a character code into its only character like this:
int grade = 83; // <<<=== 1..100
grade--;
int gradeLetter = g < 60 ? 'F' : ('A' + (100-grade)/10);
// At this point you can do the output:
cout << "Your grade is " << gradeLetter << endl;
// If you must have a string, do this:
string gradeStr(1,gradeLetter);
cout << "Your grade is " << gradeStr << endl;