0

ファイルから情報を読み取り、その情報を特定の方法で処理しようとしています。ファイルの左端に、前に空白がないすべての単語の配列を作成する必要があります。ただし、その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;
}
4

2 に答える 2

2

に渡すline-1strtok、文字列の開始前に文字へのポインタが返されます。アクセスするline[-1]と、未定義の動作が発生します。strtok文字列の先頭へのポインタを取ります。

また、ステートメント;の最後にaがあります。これにより、テストが無効になり、がであってもブロックが実行されます。if( pch = strtok(line-1," \t"))ifpchNULL

于 2012-09-15T17:15:53.147 に答える
1

ここにバグがあります: strtok(line-1," \t")

line-1のアドレスですline[-1]。これは無効なアドレスであり、それを使用すると未定義の動作が発生します。

于 2012-09-15T17:14:05.663 に答える