【问题标题】:Random ascii characters keep popping up in output随机 ascii 字符不断在输出中弹出
【发布时间】:2012-09-15 17:08:06
【问题描述】:

我正在尝试从文件中读取信息并以某种方式处理该信息。我需要在文件的最左侧制作一个所有单词的数组,这些单词前面没有空格。但是,当我尝试显示该 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;
}

【问题讨论】:

    标签: c++ io symbols


    【解决方案1】:

    您将line-1 传递给strtok,这将导致它返回一个指向字符串开始之前的字符的指针;访问 line[-1] 将产生未定义的行为。 strtok 接受一个指向字符串开头的指针。

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

    【讨论】:

    • 我想我现在不确定该怎么做。如果我拿走 -1 我会遇到分段错误。
    • 哇,非常感谢。我不敢相信这是一个简单的错误。
    • 在您使用的编译器中启用“警告”。然后你会被告知像这样的可疑问题。
    【解决方案2】:

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

    line-1line[-1] 的地址。这是一个无效地址,使用它会产生未定义的行为。

    【讨论】:

    • 如果我拿走 -1 我得到一个分段错误。关于如何解决这个问题的任何想法?
    • @cadavid4j 我认为你应该发布那个问题。它不再与这个问题有关。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-21
    • 2011-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多