从字符串变量中逐字符读取单词

Read a word char by char from string variable

本文关键字:字符 读取 单词 字符串 变量      更新时间:2023-10-16

我正在开发一个小型表达式解析器,但遇到了问题:

我想把一个单词一个字符一个字符地解析成一个字符串变量。例如,如果我们在一个字符串变量中有1个PLUS/MINUS 1,我想让PLUS/MMINUS按字符读取,并存储到另一个字符串中,以便将来使用。任何帮助都将不胜感激,因为我是CPP 的新手

您可以使用std::istringstream:的格式化输入功能

#include <iostream>
#include <sstream>
#include <string>
int main() {
std::string orig = "1 PLUS 2";  // changed to "2" to show what goes where
std::istringstream is(orig);    // put the string in an input stringstream
int a, b;
std::string word;
is >> a >> word >> b;           // extract from the stringstream
std::cout << a << 'n'
<< word << 'n'
<< b << 'n';
}

输出:

1
PLUS
2