8bit_coder
8bit_coder

Reputation: 62

If variable can't have spaces?

I am making an experimental program in batch for a simple chatting interface. In this one, I made a function where if there is the word r placed in chat, it ignores it and just redisplays the text file again. It works fine if I put r and it just refreshes, and if I put one word it works fine, but if I put a word and a space and another word, it breaks and shows the following error:

Chat(Put r for refresh):hey hi
hi was unexpected at this time.

Does anyone know how to fix this? Thanks.

Code:

@echo off
cls
cd %USERPROFILE%\Desktop\Chat
for /f "delims=" %%A in (chat.txt) do (
    set %%A
)
echo %chatt%
echo %chatp%
echo %chatn%
cd %USERPROFILE%\Desktop\Chat\Servers\%chatt%
:1
cls
type %chatn%.chat
set /p in=Chat(Put r for refresh):
if %in% == r goto 1
echo %chatp%: %in%>>%chatn%.chat
goto 1

Upvotes: 1

Views: 54

Answers (1)

Heath Raftery
Heath Raftery

Reputation: 4159

The usual way to deal with spaces in a string variables contents is to wrap it in quotes. This is the case here. When you use the variables contents with %in% the contents are inserted verbatim, so the suspect line would look like this:

if hey hi == r goto 1

It starts off okay if hey but then instead of seeing a comparison operator like == it sees hi and chokes. So wrap it all in quotes:

if "%in%" == "r" goto 1

That way it will be interpreted like

if "hey hi" == "r" goto 1

and the bat engine will know that "hey hi" should be treated as one entity.

Upvotes: 1

Related Questions