输出中不断出现随机ascii字符
Random ascii characters keep popping up in output
我正在尝试从文件中读取信息,并以某种方式处理这些信息。我需要在文件的左手边列出所有前面没有空格的单词。然而,当我试图显示那个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
测试无效,并导致块运行,即使pch
是NULL
。
这里有一个错误:strtok(line-1," t")
CCD_ 11是CCD_ 12的地址。它是一个无效的地址,使用它会产生未定义的行为。
相关文章:
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 为什么 Serial.println(<char[]>);返回随机字符?
- 字符串-C++后显示的随机字符
- 循环中的随机函数
- 在c++构造函数中使用随机字符串生成器
- 使用std::mt19937从字符串中返回一个随机单词
- 为什么std::condition_variable notify_all的工作速度比notify_one快(对于随机请
- 如何在C++中高效地构造随机骰子
- 在类中使用随机生成器时出现性能问题
- 在将数字随机生成为数组期间从内存输出随机数的数组
- C++,在int数组中输入字符串或字符会输出0,而不是ascii或error
- 将字符随机转换为大写的函数
- 为什么 vector 的随机访问迭代器给出与指针不同的内存地址?
- 为什么我的C++程序的程序集输出充满了 .ascii,没有汇编代码?
- 有没有办法通过使用十进制 ASCII 代码自动类型扣除来获取字符?
- 如何将字节数组元素替换为修改的十六进制 ASCII 符号?
- ascii 和 unicode 在处理级别有什么区别吗?
- 如何生成一个随机的 n 位数,其中 n 是任意的
- 输出中不断出现随机ascii字符
- 随机出现 ascii 字符