Help with variables.

If you have questions about any aspect of QBasic programming, or would like to help fellow programmers solve their problems, check out this board!
Post Reply
Smokehound
Newbie
Posts: 2
Joined: Thu Nov 04, 2010 9:36 am

Help with variables.

Post by Smokehound »

I am not sure if Qbasic is able to do this, but here is what I need to do.

I would like to take a variable and break it in to pieces.

Example:

X = 325

I want to cut that up to make three more variables as follows

A = 3
B = 2
C = 5

I assume there is a way to do this using something similar to the LEFT$/RIGHT$ function, but I don?t know what that would be.

Any help would be greatly appreciated.

Thanks,
Jeff
User avatar
burger2227
Veteran
Posts: 2466
Joined: Mon Aug 21, 2006 12:40 am
Location: Pittsburgh, PA

Post by burger2227 »

You can convert numbers to string numbers with:

strnum$ = STR$(number%)

STR$ leaves the space on the left with positive values or the minus sign if negative. You can LTRIM$ positive values to get rid of the space.

IF you trim it first you can use:

A$ = LEFT$(strnum$, 1): B$ = MID$(strnum$, 2, 1): C$ = RIGHT$(strnum$, 1)

LEN can tell you how many digits the number is. It will count spaces too.

sign% = SGN(number) can tell the sign with 1 meaning positive and -1 as negative.

DON'T FORGET THAT A, B and C are STRING values that require $ or DIM A AS STRING

To convert strings back to numerical values use numberA% = VAL(A$)
Please acknowledge and thank members who answer your questions!
QB64 is a FREE QBasic compiler for WIN, MAC(OSX) and LINUX : https://www.qb64.org/forum/index.php
Get my Q-Basics demonstrator: https://www.dropbox.com/s/fdmgp91d6h8ps ... s.zip?dl=0
Smokehound
Newbie
Posts: 2
Joined: Thu Nov 04, 2010 9:36 am

Post by Smokehound »

Thanks for the reply I will give that a shot.

Do you know if there is a way to do it without converting the variable to a string?
User avatar
burger2227
Veteran
Posts: 2466
Joined: Mon Aug 21, 2006 12:40 am
Location: Pittsburgh, PA

Post by burger2227 »

Yes, you can use Integer division and MOD, remainder integer division.

number = 325

hundreds = number \ 100 ' = 3

tens = (number MOD 100) \ 10 ' = 25 \ 10 = 2

ones = number MOD 10 ' = 5

When MOD returns 0, the number is evenly divisible using integer division.
Please acknowledge and thank members who answer your questions!
QB64 is a FREE QBasic compiler for WIN, MAC(OSX) and LINUX : https://www.qb64.org/forum/index.php
Get my Q-Basics demonstrator: https://www.dropbox.com/s/fdmgp91d6h8ps ... s.zip?dl=0
Post Reply