【问题标题】:Retrieve char defined in string检索字符串中定义的字符
【发布时间】:2017-10-18 05:21:41
【问题描述】:

我目前正在编写一个汇编程序和 VM 程序。我的汇编程序读入一个 .asm 文件并将其转换为我的 VM 然后运行的字节码。

目前我从我的汇编文件中读入一行,将该行分解为它的组件,然后确定该行包含什么(是指令还是指令)

getline(assemblyFile, line);

istringstream iss(line);
vector<string> instruction{
    std::istream_iterator<std::string>(iss),{}
};              

这给了我一个字符串向量,到目前为止它对我来说效果很好。如果我的指令是一个 int,我可以简单地通过说来检索它

mem[dataCounter] = stoi(instruction[VALUE]);

当我为我的字符使用 ASCII 值时,这也很有效。但是,我现在正在尝试能够提供 ASCII 表示,或者使用像

这样的符号
J       .BYT    'J'

第一个 J 是一个标签,.BYT 告诉我它是什么数据类型,我的“J”是我想要存储在我的字节数组中的字节。如果我不使用引号,

J       .BYT    J

以下效果很好

mem[dataCounter] = int(instruction[VALUE].c_str()[0]);

(给我十进制/字节值),其中指令是整行,VALUE 是索引 2。如果我使用前者,它当然会返回第一个引号。不使用引号本身可能是解决方案,但是,我在阅读特殊字符(例如空格或换行符)时也遇到了麻烦。在空格的情况下,我的指令看起来像

SPACE   .BYT    ' '

它返回一个包含四个元素的向量,“SPACE”、“.BYT”、“'”和“'”,对于我一直在尝试的换行符

NEWLN   .BYT    \n

我有三个元素,最后一个是“\n”。

在这些情况下,我还没有找到一种方法来将我试图在我的 .asm 文件中表示的字符检索到它们的等效字符/十进制值。我想继续使用字符串,因为它很方便,而且更改需要进行相当多的重构,但可以支持功能。

有哪些方法/函数可以帮助我检索这些字符,尤其是特殊字符?

【问题讨论】:

  • instruction[VALUE] 包含什么?整个字符串?我的意思是这个输入 J .BYT 'J' 例如。
  • 指令包含整行。 VALUE 是索引 2,因此指令 [VALUE] 是包含第三个元素“J”的字符串。

标签: c++ string function char


【解决方案1】:

我会使用strtok() 并谨慎对待特殊字符。

例如,我会检查标记是否为换行符,以及是否明确声明。

对于' ',我会在字符串中搜索它,如果找到,记住它的信息(例如在字符串中的起始位置),然后从字符串中删除它。之后,我会分裂成token。

仅用于演示目的的最小示例:

#include <cstdio>
#include <cstring>
#include <string>
#include <iostream>

int main ()
{
  //std::string str ="SPACE   .BYT    \n";
  //std::string str = "J       .BYT    'J'";
  std::string str ="SPACE   .BYT    ' '";
  std::size_t start_position_to_erase = str.find("' '");
  if(start_position_to_erase != std::string::npos) {
    std::cout << "Found: " << std::string(str, start_position_to_erase, start_position_to_erase+3) << std::endl;
    str.erase(start_position_to_erase, 3);
  }
  char * pch;
  printf ("Splitting string \"%s\" into tokens:\n", str.c_str());
  pch = strtok ((char*)str.c_str()," ");
  while (pch != NULL)
  {
    if(pch[0] == '\n')
        printf ("\\n");
    else
        printf ("%s\n",pch);
    pch = strtok (NULL, " ");
  }
  return 0;
}

输出:

Found: ' '
Splitting string "SPACE   .BYT    " into tokens:
SPACE
.BYT

【讨论】:

    猜你喜欢
    • 2017-01-04
    • 1970-01-01
    • 2012-02-13
    • 2013-01-20
    • 2018-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多