需要解析整型字符串并获得空白

Need to parse a string of ints and get the white space

本文关键字:串并 空白 字符串 字符 整型      更新时间:2023-10-16

我有一个充满整型数(每行上的可变数量)的文件,用空格分隔。我要解析int,然后是space,然后是int,然后是space…直到换行字符,然后从新的行开始,直到eof。一个示例文件看起来像这样:

1 1 324 234 12 123 
2 2 312 403 234 234 123 125 23 34
...
要获取整型,我可以这样做:
std::ifstream inStream(file.txt);
std::string line;
int myInt = 0;
while(getline(inStream, line)) {
    std::stringstream ss(line);
    while(ss) {
        ss >> myInt;
        //process...
    }
}

我的问题是,是否有一种简单的方法可以从ss中获得空格和尾行字符?或者我最好的办法是假设每个索引后面有一个空格,并且在ss的末尾有一个换行符?像这样:

std::ifstream inStream(file.txt);
std::string line;
int myInt = 0;
while(getline(inStream, line)) {
    std::stringstream ss(line);
    while(ss) {
        ss >> myInt;
        // process...
        // done with myInt
        char mySpace = ' ';
        // now process mySpace
    }
    char myNewLine = 'n';
    // now process myNewLine
}

如果性能不是最重要的问题,那么下面将是针对您的输入格式的通用标记器。当然,这是否是一个可行的解决方案取决于您实际想要如何处理输入。

#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
static void handle_number_string(std::string& literal) {
  if (!literal.empty()) {
    std::istringstream iss {literal};
    int value;
    if (iss >> value) {
      std::clog << "<" << value << ">";
    } else {
      // TODO: Handle malformed integer literal
    }
    literal.clear();
  }
}
int main(int argc, char** argv) {
  for (int i = 1; i < argc; i++) {
    std::string aux;
    std::ifstream istr {argv[i]};
    std::clog << argv[i] << ": ";
    while (istr.good()) {
      const int next = istr.get();
      switch (next) {
      case ' ':
        handle_number_string(aux);
        std::clog << "<SPC>";
        break;
      case 'n':
        handle_number_string(aux);
        std::clog << "<EOL>";
        break;
      default:
        aux.push_back(next);
      }
    }
    // Handle case that the last line was not terminated with 'n'.
    handle_number_string(aux);
    std::clog << std::endl;
  }
  return 0;
}

附录:我只有在绝对必要的时候才会这样做。正确处理所有可能性(多个空格,非换行空格,制表符,rn,…)将需要大量的工作。如果您实际想要处理的是逻辑标记字段分隔符行尾,那么手动解析空白似乎是错误的方法。如果您的程序仅仅因为用户对输入文件中的列进行了对齐(因此使用了可变数量的空格)而崩溃,那将是令人遗憾的。

试试这样:

std::ifstream inStream(file.txt);
std::string line;
int myInt;
while (std::getline(inStream, line))
{
    std::stringstream ss(line);
    ss >> myInt;
    if (ss)
    {
        do
        {
            // process...
            // done with myInt
            ss >> myInt;
            if (!ss) break;
            char mySpace = ' ';
            // now process mySpace
        }
        while (true);
    }
    char myNewLine = 'n';
    // now process myNewLine
}
相关文章: