输出中不断出现随机ascii字符

Random ascii characters keep popping up in output

本文关键字:随机 ascii 字符 输出      更新时间:2023-10-16

我正在尝试从文件中读取信息,并以某种方式处理这些信息。我需要在文件的左手边列出所有前面没有空格的单词。然而,当我试图显示那个char数组的内容时,我总是得到非常奇怪的输出。

这是示例输入:

# Sample Input
    LA 1,3
    LA 2,1
TOP    NOP
    ADDR 3,1
    ST 3, VAL
    CMPR 3,4
    JNE TOP
    P_INT 1,VAL
    P_REGS
    HALT
VAL     INT 0
TAN     LA  2,1

例如,当我运行程序时,我的输出应该是:

TOP
VAL
TAN

相反,我得到了:

a
aTOP
aVAL
aTAN
a
a

我不知道为什么会发生这种事。我所做的任何微小的改变实际上都没有帮助,它们只是改变了我预期输出之前的内容。有时它是ASCII值0或20个字符。希望有人能帮我解决这个问题,因为这让我抓狂。

这是我的代码:

#include <string>
#include <iostream>
#include <cstdlib>
#include <string.h>
#include <fstream>
#include <stdio.h>

using namespace std;

int main(int argc, char *argv[])
{
// If no extra file is provided then exit the program with error message
if (argc <= 1)
{
    cout << "Correct Usage: " << argv[0] << " <Filename>" << endl;
    exit (1);
}
// Array to hold the registers and initialize them all to zero
int registers [] = {0,0,0,0,0,0,0,0};
string memory [16000];
string symTbl [1000][1000];
char line[100];
char label [9];
char opcode[9];
char arg1[256];
char arg2[256];
char* pch;
// Open the file that was input on the command line
ifstream myFile;
myFile.open(argv[1]);

if (!myFile.is_open())
{
    cerr << "Cannot open the file." << endl;
}
int counter = 0;
int i = 0;
while (myFile.good())
{
    myFile.getline(line, 100, 'n');
    // If the line begins with a #, then just get the next line
    if (line[0] == '#')
    {
        continue;
    }

    // If there is a label, then this code will run
    if ( line[0] != 't' && line[0]!=' ')
    {
        if( pch = strtok(line-1," t"));
            {
                strcpy(label,pch);
                cout << label << endl;
            }
        if (pch = strtok(NULL, " t"))
        {
            strcpy(opcode,pch);
        }
        if (pch = strtok(NULL, " t,"))
        {
            strcpy(arg1,pch);
        }
        if (pch = strtok(NULL, ","))
        {
            strcpy(arg2, pch);
        }
    }

}

return 0;
}

您正在将line-1传递给strtok,这将导致它返回一个指向字符串开头之前的字符的指针;访问CCD_ 3将产生未定义的行为。strtok获取一个指向字符串开头的指针。

if( pch = strtok(line-1," t"))语句的末尾还有一个;,它使if测试无效,并导致块运行,即使pchNULL

这里有一个错误:strtok(line-1," t")

CCD_ 11是CCD_ 12的地址。它是一个无效的地址,使用它会产生未定义的行为。