1

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.

4

2 回答 2

2

您可以使用以下INSTR功能:

'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

INSTR 的语法如下所示:

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

如果startOffset%省略,则从字符串的开头开始搜索。您要查找的字符是CHR$(10). QBasic 使用这种 CHR 语法而不是 Java 等已知的转义。

在这里您可以找到有关 INSTR 功能的其他帮助:

如果您只想计算文本文件的行数而不是在字符串中查找 LF 字符,您可以执行以下操作:

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

但请注意:LINE INPUTcount 方法仅适用于 DOS/Windows 行尾 (CrLf = Chr$(13)+Chr$(10) = \r\n)。如果文本文件有类似 UNIX 的行结尾(仅限 \n),则文件中的所有行都将变为单个字符串,并且上面的计数脚本将始终返回“1 行”作为结果。

在这种情况下,另一种方法是以BINARY模式打开文件并逐字节检查。如果遇到 Chr$(10),则增加行数变量。

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
于 2013-06-09T11:38:42.053 回答
0

使用二进制文件 i/o 计算文件中行数的示例程序。

REM sample program to count lines in a file in QB64.
' declare filename buffer
CONST xbuflen = 32767 ' can be changed
DIM SHARED xbuffer AS STRING * XBUFLEN
DIM SHARED Lines.Counted AS DOUBLE
' get filename
PRINT "Enter filename";: INPUT Filename$
' start file count
IF _FILEEXISTS(Filename$) THEN
    X = FREEFILE
    OPEN Filename$ FOR BINARY SHARED AS #X LEN = xbuflen
    IF LOF(X) > 0 THEN
        DO UNTIL EOF(X)
            ' get file buffer
            GET X, , xbuffer
            ' count bytes in buffer
            FOR L = 1 TO xbuflen
                IF MID$(xbuffer, L, 1) = CHR$(10) THEN
                    Lines.Counted = Lines.Counted + 1#
                END IF
            NEXT
        LOOP
    END IF
    CLOSE #X
END IF
PRINT "Lines in file"; Lines.Counted
END
于 2018-03-01T04:54:54.370 回答