batch file equivalent for this code
-
21-08-2019 - |
Question
HI i want to implement this C code in batch file
int i;
scanf("%d", &i);
for(int j = 0;j<i;j++)
{
scanf("%d",&j);
printf("%d",j);
}
I would run the c program using > redirection in DOS so that the printed output comes to me in a file. I want to do the same thing in my batch file where i could write something like
echo %variable% >> file
but it doesn't work for me
@echo off
for %%i in (1 2 3) do (
set /p c=enter a name?
echo %%i
echo %c% >> file.txt
)
what is wrong?
Solution
That can't work since you need delayed variable expansion as you try to refer to a changing variable in the if
block. You can try the following:
@echo off
setlocal enabledelayedexpansion
for %%i in (1 2 3) do (
set /p c=enter a name?
echo %%i
echo !c! >> file.txt
)
as this would evaluate c
only when the code is run, not when the line (in this case the complete if
statement) is parsed.
A straightforward translation of your C code in batch would probably look more like the following, though:
@echo off
set /p i=
:loop
set /p j=
echo %j%
set /a j+=1
if %j% LSS %i% goto loop
You can add prompts if you like, though the C program didn't have them either :). And now you could pipe the output of the batch program as a whole or just add a >> file
in there for good measure.