dcsimg
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 22

Thread: unexpected behavior of integer variable

  1. #1
    Join Date
    Dec 2019
    Posts
    23

    unexpected behavior of integer variable

    Hello,

    Why is the int variable i ignored at 0 and recognized as zero at 10? I just started learning C++ so if there's a cleaner more efficient way to convert integer values to string then please don't hesitate to tell me.

    Ron

    Code:
    #include <iostream>
    #include <string>
    
    int i = 0;
    
    std::string numstr;
    
    int main()
    {
      for (i = 0; i < 9; i += 1)
      {
        if (i = 10) numstr.append("0");
        if (i = 1) numstr.append("1");
        if (i = 2) numstr.append("2");
        if (i = 3) numstr.append("3");
        if (i = 4) numstr.append("4");
        if (i = 5) numstr.append("5");
        if (i = 6) numstr.append("6");
        if (i = 7) numstr.append("7");
        if (i = 8) numstr.append("8");
        if (i = 9) numstr.append("9");
      }
      std::cout << numstr;
      std::cin.get();
      return 0;
    }

  2. #2
    Join Date
    Feb 2017
    Posts
    506

    Re: unexpected behavior of integer variable

    Quote Originally Posted by OldRon View Post
    if (i = 10) numstr.append("0");
    That line is wrong in two ways. It should be,
    Code:
        if (i == 0) numstr.append("0");
    = is an assignment, == checks for equality.

    There is a standard function to_string you can use,

    https://en.cppreference.com/w/cpp/st...ring/to_string

  3. #3
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,208

    Re: unexpected behavior of integer variable

    If you don't already have a book on modern C++, you may want to pick up one. It would go nicely with a modern free compiler.

  4. #4
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    6,972

    Re: unexpected behavior of integer variable

    In C/C++, = is assignment and == is equality test. So:

    Code:
    if (i = 10) numstr.append("0");
    means first set i to 10. If the result is true (ie non-zero), which it is here as 10 is non-zero, then execute the following statement (the .append() ).

    Also note that i will never be 10. The only values i will have are 0 to 8 inclusive. Also, i += 1 would usually be written ++i (pre-increment). There is also post-increment (i++). Used by themselves the result is the same but for reasons you'll learn much later in your journey into the C++ world, the pre-increment is preferable. The difference is in the result. Consider:

    Code:
    	int i = 2;
    
    	auto i1 = ++i;
    
    	std::cout << i << '\t' << i1 << std::endl;
    
    	auto i2 = i++;
    
    	std::cout << i << '\t' << i2 << std::endl;
    giving:

    Code:
    3       3
    4       3
    In both cases, i has been incremented by 1 - but in the case of i1 this has the value after the increment whereas i2 has the value before the increment.

    i and numstr don't need to be defined as global variables - outside of the function main(). It's good practice to always define variables as close as possible to where they are used so that their scope is as small as possible. Also, for a for loop a variable can be defined within the for loop so that it's scope is only the for loop.

    When converting a single digit in ASCII, as here, then remember that the digits are sequential starting at '0'. So 0 is '0' + 0, 1 is '1' + 1 etc.

    The string class supports the operator += to append to the end of the specified string (.append() does the same but with a slightly different set of permitted operands).

    Consider:

    Code:
    #include <iostream>
    #include <string>
    
    int main()
    {
    	std::string numstr;
    
    	for (size_t i = 0; i < 9; ++i)
    		numstr += '0' + i;
    
    	std::cout << numstr;
    	//std::cin.get();
    }
    If you want to convert a number that isn't a positive single digit (eg 123, -11), then one way would be as Wolle suggested in post #2 to use to_string(). Consider:

    Code:
    #include <iostream>
    #include <string>
    
    int main()
    {
    	for (size_t i = 111; i < 999; i += 111) {
                    const std::string numstr = std::to_string(i);
    		std::cout << numstr << std::endl;
            }
    
            //std::cin.get();
    }
    Obviously, in this simple example the variable numstr is not actually needed. However, it highlights an important concept in C++ that variables whose content shouldn't change after their initialization should be defined as const.
    Last edited by 2kaud; December 23rd, 2019 at 05:30 AM.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++17 Compiler: Microsoft VS2019 (16.4.2)

  5. #5
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    6,972

    Re: unexpected behavior of integer variable

    Quote Originally Posted by Arjay View Post
    If you don't already have a book on modern C++, you may want to pick up one. It would go nicely with a modern free compiler.
    My favourite book for learning C++ is Beginning C++17 From Novice To Professional by Ivor Horton. https://www.amazon.co.uk/Beginning-C...s=books&sr=1-8

    Also consider this web site https://www.learncpp.com/
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++17 Compiler: Microsoft VS2019 (16.4.2)

  6. #6
    Join Date
    Dec 2019
    Posts
    23

    Re: unexpected behavior of integer variable

    Quote Originally Posted by 2kaud View Post
    In C/C++, = is assignment and == is equality test. So:

    Code:
    if (i = 10) numstr.append("0");
    means first set i to 10. If the result is true (ie non-zero), which it is here as 10 is non-zero, then execute the following statement (the .append() ).

    Also note that i will never be 10. The only values i will have are 0 to 8 inclusive. Also, i += 1 would usually be written ++i (pre-increment). There is also post-increment (i++). Used by themselves the result is the same but for reasons you'll learn much later in your journey into the C++ world, the pre-increment is preferable. The difference is in the result. Consider:

    Code:
    	int i = 2;
    
    	auto i1 = ++i;
    
    	std::cout << i << '\t' << i1 << std::endl;
    
    	auto i2 = i++;
    
    	std::cout << i << '\t' << i2 << std::endl;
    giving:

    Code:
    3       3
    4       3
    In both cases, i has been incremented by 1 - but in the case of i1 this has the value after the increment whereas i2 has the value before the increment.

    i and numstr don't need to be defined as global variables - outside of the function main(). It's good practice to always define variables as close as possible to where they are used so that their scope is as small as possible. Also, for a for loop a variable can be defined within the for loop so that it's scope is only the for loop.

    When converting a single digit in ASCII, as here, then remember that the digits are sequential starting at '0'. So 0 is '0' + 0, 1 is '1' + 1 etc.

    The string class supports the operator += to append to the end of the specified string (.append() does the same but with a slightly different set of permitted operands).

    Consider:

    Code:
    #include <iostream>
    #include <string>
    
    int main()
    {
    	std::string numstr;
    
    	for (size_t i = 0; i < 9; ++i)
    		numstr += '0' + i;
    
    	std::cout << numstr;
    	//std::cin.get();
    }
    If you want to convert a number that isn't a positive single digit (eg 123, -11), then one way would be as Wolle suggested in post #2 to use to_string(). Consider:

    Code:
    #include <iostream>
    #include <string>
    
    int main()
    {
    	for (size_t i = 111; i < 999; i += 111) {
                    const std::string numstr = std::to_string(i);
    		std::cout << numstr << std::endl;
            }
    
            //std::cin.get();
    }
    Obviously, in this simple example the variable numstr is not actually needed. However, it highlights an important concept in C++ that variables whose content shouldn't change after their initialization should be defined as const.
    Thank you for your constructive input. So that you might better understand my needs when I ask for help my project is writing programs for an Arduino UNO. It used to be building and writing the OS for CNC machine tool controls but health issues curtailed that. I'm familiar with to_string but it never dawned on me to use it in this application. However, that code is a prototype for building a string that will be populated by the keypad and then converted to a double for calculations. Therefore, the digit added to the string will already be a string. In the prototype the 'for' statement is simply serving as my keypad. I will not be using a leading 0 so the fact that "i = 0" has to be "i = 10" in order to add "0" to the string isn't really a problem. I just wanted to know why that is the case. Thank you for your explanation.... and yes, I'm 10 inches into a 10,000 mile journey that I won't live long enough to complete.

    Code:
    /*
    String to Double Precision
    */
    
    #include <iostream>
    #include <iomanip>
    #include <string>
    
    int i;
    std::string numstr;
    
    void main()
    {
      for (i = 0; i < 9; i ==1)
      {
        if (i = 0) numstr.append("0");
        if (i = 1) numstr.append("1");
        if (i = 2) numstr.append("2");
        if (i = 3) numstr.append("3.");
        if (i = 4) numstr.append("4");
        if (i = 5) numstr.append("5");
        if (i = 6) numstr.append("6");
        if (i = 7) numstr.append("7");
        if (i = 8) numstr.append("8");
        if (i = 9) numstr.append("9");
      }
      std::cout << std::setprecision(32) << (stod(numstr) * 3);
      std::cin.get();
    }
    Name:  Double.jpg
Views: 32
Size:  13.3 KB
    Last edited by OldRon; December 23rd, 2019 at 07:25 AM.

  7. #7
    Join Date
    Dec 2019
    Posts
    23

    Re: unexpected behavior of integer variable

    Quote Originally Posted by 2kaud View Post
    My favourite book for learning C++ is Beginning C++17 From Novice To Professional by Ivor Horton. https://www.amazon.co.uk/Beginning-C...s=books&sr=1-8

    Also consider this web site https://www.learncpp.com/
    Books are like newspaper, so yesterday. My favorite book is Google. Much easier on the eyes.

  8. #8
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,208

    Re: unexpected behavior of integer variable

    Quote Originally Posted by OldRon View Post
    Books are like newspaper, so yesterday. My favorite book is Google. Much easier on the eyes.
    What books offer, that Google doesn't, is structured learning.

  9. #9
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    6,972

    Re: unexpected behavior of integer variable

    You are aware that your code in post #6 is still wrong for the reasons discussed in posts #2 and #4? Consider:

    Code:
    /*
    String to Double Precision
    */
    
    #include <iostream>
    #include <iomanip>
    #include <string>
    
    int i;
    std::string numstr;
    
    void main()
    {
    	for (i = 0; i < 9; i += 1)
    	{
    		if (i == 0) numstr.append("0");
    		if (i == 1) numstr.append("1");
    		if (i == 2) numstr.append("2");
    		if (i == 3) numstr.append("3.");
    		if (i == 4) numstr.append("4");
    		if (i == 5) numstr.append("5");
    		if (i == 6) numstr.append("6");
    		if (i == 7) numstr.append("7");
    		if (i == 8) numstr.append("8");
    		if (i == 9) numstr.append("9");
    	}
    	std::cout << std::setprecision(32) << (stod(numstr) * 3);
    	std::cin.get();
    }
    giving the output

    Code:
    370.37033999999999878127709962428
    The correct answer is 370.37034. The discrepancy is due to floating point rounding and that you have specified 32 digit precision.

    If 9 digits of precision are used:

    Code:
    	std::cout << std::setprecision(9) << (stod(numstr) * 3);
    then the output is as expected:

    Code:
    370.37034
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++17 Compiler: Microsoft VS2019 (16.4.2)

  10. #10
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    6,972

    Re: unexpected behavior of integer variable

    Quote Originally Posted by OldRon View Post
    Books are like newspaper, so yesterday. My favorite book is Google. Much easier on the eyes.
    Note that not everything you read on the Internet regarding C++ is good practice - or even correct.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++17 Compiler: Microsoft VS2019 (16.4.2)

  11. #11
    Join Date
    Feb 2017
    Posts
    506

    Re: unexpected behavior of integer variable

    Quote Originally Posted by OldRon View Post
    I'm 10 inches into a 10,000 mile journey that I won't live long enough to complete.
    I googled for Arduino UNO,

    https://store.arduino.cc/arduino-uno-rev3

    and when writing code for devices like this I would say C++ may be overkill.

    I would concentrate on the C part of C++. It will cut your 10,000 mile journey down to maybe 100 miles and if you have some previous programming experience with a procedural language it's only 1 mile to go, a cake walk really.

    So I suggest you concentrate on C only and cherry pick algorithms & data structures from the C++ standard library on a need to have basis. The latter will require you to look a little into C++ but no way near as much as if you were to program in modern C++.
    Last edited by wolle; December 23rd, 2019 at 12:20 PM.

  12. #12
    Join Date
    Dec 2019
    Posts
    23

    Re: unexpected behavior of integer variable

    2kaud,

    I did not realize that I pasted the code with setprecision(32). While the number was accurate it would be foolish to use it for a calculation. Actually my program won't use setprecision(). When the original formula result printed out as being 370.37 then I became concerned because that would cause intolerable errors such as rotary indexing a part 29 times at 12 intervals and then have the final index position come up short of 348. Possessing so little knowledge of C++ I had to to make sure that that the variables stored the assigned value. For that reason I assigned the result of the formula below to double test and then printed it out. Undoubtedly my method are clumsy but I will end up with a working solution for my needs.

    Code:
    test = sqrt((stod(numstr) * 3) / 9);
    std::cout << std::setprecision(9) << test; -->  6.41500296

  13. #13
    Join Date
    Dec 2019
    Posts
    23

    Re: unexpected behavior of integer variable

    wolle,

    I have programmed in C but it was limited to dynamic linked libraries and a could of drivers for my CNC machine tool control software. That was over 15 years ago but I do recall that I wanted nothing to with C++ back then. I'll have to blow the dust off of those files and see if there's anything that I can use for a start up prototype. One of the drivers facilitate querying the PC stats such as processor temperature and fan speed. Passing the stats to the PC screen was pretty hairy. Thanks for the tip.

  14. #14
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    6,972

    Re: unexpected behavior of integer variable

    While the number was accurate it would be foolish to use it for a calculation.
    setprecision() is only relevant for stream insertion (<<). It has no effect on how the number(s) are stored internally which for double is 15 stable integral decimal digits.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++17 Compiler: Microsoft VS2019 (16.4.2)

  15. #15
    Join Date
    Dec 2019
    Posts
    23

    Re: unexpected behavior of integer variable

    2kaud,

    That is the conclusion I came to when I assigned the value of String Converted to Double value to a double variable and then printed the variable using setprecision(). On day five of my study of C++ I wrote the program that will control a rotary table that will be used for the fourth axis on a CNC milling machine. That hardly compares to my first Visual Basic 6.0 program which was the entire operating system for a CNC macine tool control. In order to learn a person must first be willing to expose their lack of knowledge, aka ignorance. For those that took the time to answer my stupid questions; Merry Christmas and may you have many Happy New Years.

    Ron

Page 1 of 2 12 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width




On-Demand Webinars (sponsored)