Search code examples
newlineqbasic

New line char in qbsic?


I know that my question is very basic,but I'm not familier with qbasic,so excuse me.My question is:

How I can detect new line char in a string variable in qbasic?In java we have to find '\n' char,but what is in qbasic?Really I want to read a text file and detect it's lines.Thank you.


Solution

  • You can use the INSTR function:

    'Sample text
    Dim myText As String
    myText = "Hello World!" + CHR$(10) + "This is a new line."
    
    'Find new line character \n (line feed LF)
    Dim newLinePosition As Integer
    newLinePosition = Instr(myText, CHR$(10))
    If (newLinePosition >= 1) Then
        Print "Yes, a LF character was found at char no# "; Ltrim$(Str$(newLinePosition))
    Else
        Print "No LF character was found. :("
    End If
    
    Sleep: End
    

    The syntax of INSTR looks like this:

    pos% = INSTR ( [startOffset%,] haystack$, needle$ )
    

    If startOffset% is omitted, it starts its search at the begin of the String. The character you look for is CHR$(10). QBasic uses this CHR-Syntax instead of the escaping known from Java etc.

    Here you can find additional help on the INSTR function:

    If you just want to count the lines of a text file rather than looking for LF characters in a string, you could do something like this:

    Dim lineCount As Integer
    lineCount = 0
    
    Dim f As Integer
    f = FreeFile  ' Automatic detection of next free file handle
    
    Open "MYTEXT.TXT" For Input As #f
    Do Until Eof(f)
        Line Input #f, temp$
        lineCount = lineCount + 1
    Loop
    Close #f
    
    Print "The text file consists of "; Ltrim$(Str$(lineCount)); " lines."
    Sleep: End
    

    But watch out: The LINE INPUT count method will only work for DOS/Windows line endings (CrLf = Chr$(13)+Chr$(10) = \r\n). If the text file has UNIX-like line endings (\n only), all lines in the file will become a single string and the counting script above will always return "1 lines" as result.

    An alternative approach in that case is opening the file in BINARY mode and checking it byte by byte. If Chr$(10) is encountered, than a line count variable is incremented.

    DIM lineCount AS INTEGER
    lineCount = 0
    
    DIM f AS INTEGER
    f = FREEFILE  ' Automatic detection of next free file handle
    
    DIM buffer AS STRING
    buffer = SPACE$(1)
    
    OPEN "MYTEXT.TXT" FOR BINARY AS #f
    DO UNTIL EOF(f)
        GET #f, , buffer
        IF (buffer = CHR$(10)) THEN
            lineCount = lineCount + 1
        END IF
    LOOP
    CLOSE #f
    
    PRINT "The text file consists of "; LTRIM$(STR$(lineCount)); " lines."
    SLEEP: END