【问题标题】:Odd symbols in terminal when running program运行程序时终端出现奇数符号
【发布时间】:2012-09-15 09:08:56
【问题描述】:

这个程序的重点是从文件中读取指令列表。在第一次通过时,我只是在他们面前得到最左边的命令(唯一没有\t 的命令)。我已经设法做到了,但是我遇到的问题是,当我测试我的代码以查看是否正确复制了 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

我收到的奇怪输出是:

D
D
D
DTOP
DTOP
DTOP
DTOP
DTOP
DTOP
DTOP
DTOP
DVAL
D
D

我只是不确定我是如何得到如此奇怪的输出的。这是我的代码:

#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], label[9];
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 (line[0] == '#')
    {
        continue;
    }


    if ( line[0] != '\t' && line[0]!=' ')
    {
        pch = strtok(line-1," \t\n");
        strcpy(label,pch);
    }

    cout << label<< endl;

        }



return 0;
}

任何帮助将不胜感激。

【问题讨论】:

  • 预期的输出是什么?
  • @JoachimPileborg 预期的输出是原始输出中的所有内容,D 除外。

标签: c++ io symbols


【解决方案1】:

也许您错过了if ( line[0] != '\t' &amp;&amp; line[0]!=' ')else 案例,您需要在打印之前为label 赋予一些价值。

【讨论】:

  • 我不确定这是否与此有关。我得到了正确的输出,我只是收到了覆盖它们的奇怪字符。
  • @cadavid4j:你能提到奇怪的字符吗?还是我想念他们?
  • D 肯定很奇怪,当我从 strtok() 中的分隔符列表中删除 \n 时,换行符也会显示在我的输出上。
【解决方案2】:

一个主要问题是您没有初始化label 数组,因此它可以包含任何随机数据,然后您将其打印出来。另一个问题是您每次迭代都会打印标签,即使您没有获得新标签。

您的代码还有一些其他问题,例如没有检查strtok 是否返回NULL,您应该真正使用while (myFile.getline(...)) 而不是while (myFile.good())

找出主要问题的原因的最佳方法是在调试器中运行程序,并逐行执行。然后你会看到发生了什么,并且可以检查变量以查看它们的内容是否是它应该是的。哦,别再使用字符数组了,尽可能多地使用std::string

【讨论】:

    猜你喜欢
    • 2021-03-28
    • 2014-03-06
    • 2017-09-28
    • 2014-02-09
    • 1970-01-01
    • 2011-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多