Home > Back-end >  Sum in batch script
Sum in batch script

Time:10-29

How can I make the sum of the imputed numbers given by the user from the keyboard ? I tried a for loop but is endless. I cannot figure out a break statement.

::@ECHO OFF
setlocal EnableDelayedExpansion
set /p X=
SET /A suma=0
:Loop
FOR %%G IN (%X%) DO (
    IF %%G GTR 0 (
        SET /A suma=%suma% %%G
    
    )

)
SHIFT
GOTO Loop
:completed
echo %suma%

What i want to do is to make the program more user friendyl like echo somthing for the user to know it is supposed to write somthing. I know the correct code for this question, but the numbers are given as parameters in the command (syntax: script.bat parameter1 parameter2 parameter3).

::@ECHO OFF
SET /A suma=0
:Loop
IF "%1"=="" GOTO completed
FOR %%F IN (%1) DO (
    IF %1 GTR 0 (
        SET /A suma=%suma% %1
    )
)
SHIFT
GOTO Loop
:completed
echo %suma%

Please give me any idea for the breaking statement in the first example or how can I modify the code to take the numbers from the users imput variable and not as paramaters.

Thank you.

CodePudding user response:

SET /A suma=0
set "X=%*"
if not defined X set /p "X=No parameters detected "
if not defined X ECHO No user-input detected&goto completed
FOR %%G IN (%X%) DO (
    IF %%G GTR 0 (
        SET /A suma=suma %%G
    
    )

)
:completed
echo %suma%

%* means the command-line tail. If no tail, then ask user for input. If still no data, issue message and show result.

shift moves the command line tail one position, so %2 becomes %1, etc. You haven't provided a test to exit the routine - and the command-line tail is presumably empty, so you are shifting it (which does nothing) and looping.

The for...%%G.. processes the entire list %X%, so there's no point in the shift/loop - the data has already been processed.

  • Related