views:

231

answers:

1

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?

+3  A: 

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.

Joey
Anirudh Goel
Then this code already does what you want. I misread the old code as printf("%i", j) before, so I implemented accordingly. Hey, even my variables are named the same. As far as I can tell, my batch files does the same as the C program.
Joey