【问题标题】:How to use Input String Stream with symbols seperating strings instead of spaces?如何将输入字符串流与分隔字符串而不是空格的符号一起使用?
【发布时间】:2019-01-23 03:31:18
【问题描述】:

注意:我刚刚了解了 Getline 和 Streams。

我不能用空格分隔名字、姓氏和年龄,我怎么能用 ^ 或 -- 分隔它们?

有这个功能吗?这是一个愚蠢的问题吗?如果是,为什么?

-这个问题的原因是因为我要制作一个求解多项式导数的函数,结果惨遭失败。

int main() {
  istringstream inSS;       // Input string stream
  string lineString;        // Holds line of text
  string firstName;         
  string lastName;         
  int    userAge;          


  getline(cin, lineString);


  inSS.str(lineString);


  inSS >> firstName;
  inSS >> lastName;
  inSS >> userAge;

  return 0;
}

【问题讨论】:

  • 我不明白您为什么必须更改标准格式。如果您真正打算解决多项式导数,最好针对该问题提出问题
  • std::getline has an overload with a third parameter 允许您将默认换行符分隔符更改为您想要使用的任何其他字符。如果你想在'^'上拆分,你可以getline(inSS , firstName, '^');。不要忘记在使用您阅读的内容之前测试流状态,以确保您确实阅读了一些内容。感谢operator boolwhile (getline(inSS , tempstring, '^')) { use tempstring } 可以非常方便。

标签: c++ getline sstream


【解决方案1】:

免费功能getline 还提供自定义分隔符,如 user4581301 所说。但是,它只会提取 strings 并且您还有 int

可以在这个答案中找到类似的解决方案,我已经修改了代码以满足您的需求:changing the delimiter for cin (c++)

您可以使用imbue 来自定义分隔符。下面是一个简单的例子:

#include <locale>
#include <iostream>

template<char Delim>
struct alternativeDelimiter : std::ctype<char> {
  alternativeDelimiter() : std::ctype<char>(get_table()) {}

  static mask const* get_table()
  {
    static mask rc[table_size];
    rc[Delim] = std::ctype_base::space;
    return &rc[0];
  }
};

int main() {
  using std::string;
  using std::cin;
  using std::locale;

  cin.imbue(locale(cin.getloc(), new alternativeDelimiter<'^'>));

  string word;
  while(cin >> word) {
    std::cout << word << "\n";
  }
}

imbue 确实拥有ctype 的所有权,所以不用担心自己调用 delete。

如果输入some^text,则输出为

some
text

当然,您也可以在示例中使用它。

如果您通过编写类似于第 11 行 (rc[Delim] = std::ctype_base::space) 的行来扩展表格,仅更改 Delim,您可以有多个字符,这些字符将被解释为空格。

不过,我不确定这在多大程度上解决了您最初编写数学解析器的问题。一般术语涉及“解析器”和“词法分析器”的概念,您可以研究这些概念以构建可靠的数学求解器。希望它也有帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-17
    相关资源
    最近更新 更多