【问题标题】:How to parse a string to multiple types in c++?如何在c ++中将字符串解析为多种类型?
【发布时间】:2017-06-25 09:40:44
【问题描述】:

cin >> *integerVar >> *charVar; 可以正确读取像“25 b”这样的输入。使用现有字符串执行此操作的最简单方法是什么(我可以通过拆分然后解析每个部分来手动完成,但更好的方法是什么)?

【问题讨论】:

  • std::stringstream parser("My source string"); 现在您可以像使用cin 一样使用parser。文档:en.cppreference.com/w/cpp/io/basic_stringstream
  • 你为什么使用指针? C++ 语言不是 C# 或 Java;您不需要对每个变量或实例都使用运算符 new

标签: c++ string parsing c++11


【解决方案1】:

使用istringstream 之类的,例如:

#include <string>
#include <sstream>

int main(void)
{
    std::istringstream ss("25 b");
    int x; std::string bstr;

    ss >> x >> bstr;

    return 0;
}

// note that std:istringstream allows ss >> x, but not ss << "some value".
// if you want to support both reading and writing, use a stringstream (which would then support ss >> x as well as ss << "some value")

【讨论】:

  • 我们不应该使用istringstream作为更专业的类吗?
  • @HolyBlackCat:如果你只想阅读,我认为istringstream 更能表达意图,但stringstream 也可以。
  • @HolyBlackCat:是的,这样会更好;更正了答案;感谢您的评论。
【解决方案2】:

通过使用std::stringstream

std::stringstream myStr{"25 b"};
myStr >> *integerVar >> *charVar;

【讨论】:

    【解决方案3】:

    您可以使用stringstreamstring(模板)类:

    #include <iostream>
    #include <string>
    #include <sstream>
    
    int main() {
        std::string s;
        std::getline(std::cin, s);
        std::stringstream ss(s);
        int n;
        char c;
        ss >> n >> c;
        return 0;
    }
    

    【讨论】:

      【解决方案4】:

      您可以使用sscanf,它的作用与 scanf 完全相同,但使用字符串而不是 STD 输入

      #include<iostream>
      #include<stdlib>
      #include<stdio>
      int main(){
          std::string str;
          char character;
          int intnumber;
          cin >> str;
          sscanf (str.c_str(), "%d%c", &intnumber, &character);
      }
      

      【讨论】:

      • 最好举个例子,因为这需要对string 进行一些按摩才能工作,而scanf 和朋友在输入错误的数据类型时是出了名的盲目。
      • @user4581301 这样的东西好吗?
      • 非常接近。建议在通话中使用std::string 代替char * 代替strchar 代替char * 代替charactersscanf (str.c_str(), "%d%c", &amp;intnumber, &amp;character);。因为否则您将使用一些未初始化的指针(以及调用时的额外寻址级别)。
      • 对,我其实是尽量使用最基本的c。谢谢你的cmets,虽然
      • 不用担心,但请注意这是一个 C++ 问题,而不是 C 问题。 stringstream 将捕获您在编译时使用 sscanf 可能犯的所有(或大部分)错误。 sscanf 在运行时可能会编译并做一些奇怪的事情,所以不推荐使用它。
      猜你喜欢
      • 2019-02-15
      • 2010-09-16
      • 1970-01-01
      • 1970-01-01
      • 2011-08-30
      • 2012-07-03
      • 2013-06-13
      • 1970-01-01
      • 2011-07-18
      相关资源
      最近更新 更多