【问题标题】:Reading text files with different parameters with spaces用空格读取不同参数的文本文件
【发布时间】:2020-04-05 14:50:58
【问题描述】:

文本文件

690104014431 谭守明男

730302027761 安德鲁·谭男

880502066642 Sally Indera Ong 女

ifstream theFile("PersonalInfo.txt");`

string n;
string i;
string g;

while(theFile >> i >> n >> g)

{ cout

上面最上面的部分是我试图读入这个程序的文本文件。由于名称有空格,部分名称进入性别或身份。我可以知道如何解决这个问题吗?名称之间最多有两到四个空格。

【问题讨论】:

    标签: c++


    【解决方案1】:

    由于您有一个简单的模式要匹配,您可以使用regex。例如

    int main()
    {
        std::string s = "343545 john doe male";
        std::regex r(R"((\d+)\s+(.+)\s+(\w+))");
        std::smatch m;
        std::regex_match(s, m, r);
        std::cout << "Name: " << m[2].str() << std::endl;
        std::cout << "ID: " << m[1].str() << std::endl;
        std::cout << "Gender: " << m[3].str() << std::endl;
    }
    

    打印

    Name: john doe
    ID: 343545
    Gender: male
    

    【讨论】:

      【解决方案2】:

      我们介绍istringstream:

      std::string line;
      while(getline(theFile, line)){
          std::istringstream ss(line);
          std::string part;
          ss >> part;
          i = part;
          while(ss >> part){
              if(part != "Male" || part != "Female"){
                 n += part;
              }else{
                 g = part;
              }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-10-08
        • 1970-01-01
        • 2011-11-09
        • 1970-01-01
        • 2013-12-24
        • 1970-01-01
        相关资源
        最近更新 更多