0

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;
}
Community
  • 1
  • 1
Jake2k13
  • 231
  • 3
  • 8
  • 23

2 Answers2

3
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++?.

Community
  • 1
  • 1
herohuyongtao
  • 49,413
  • 29
  • 133
  • 174
1

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?

Jake2k13
  • 231
  • 3
  • 8
  • 23
  • 2
    The original code outputs `100` (the correct answer) and immediately after that the value of a multi-character literal `'.\n'`, which is interpreted as an `int`: http://stackoverflow.com/questions/7459939/what-do-single-quotes-do-in-c-when-used-on-multiple-characters –  Feb 26 '14 at 18:29