SVN / public / code / vorlesung-09 / StringViewDemoMain.cpp

Revision 8201
Date
Committerhb1003
Download
// Copyright 2026, University of Freiburg
// Chair of Algorithms and Data Structures
// Author: Hannah Bast <bast@cs.uni-freiburg.de>

#include "Timer.h"
#include <fstream>
#include <iostream>
#include <string>

// Simplistic check that the geo `POINT` is valid.
void checkThatPointIsValid(std::string_view point) {
  // void checkThatPointIsValid(const std::string& point) {
  if (!point.starts_with("POINT(") || !point.ends_with(")")) {
    std::terminate();
  }
}

// Parse one of the TSV files for Ü9 and demonstrate the use and benefits of
// `std::string_view`.
int main(int argc, char **argv) {
  // Parse command line arguments.
  if (argc != 2) {
    std::cerr << "Usage: " << argv[0] << " <file.tsv>" << std::endl;
    return 1;
  }
  std::string filename = argv[1];

  // Read the file line by line.
  std::ifstream tsvFile(filename);
  std::string line;
  size_t lineNumber = 0;
  while (std::getline(tsvFile, line)) {
    lineNumber++;
    size_t pos = line.find('\t');
    if (pos == std::string::npos) {
      std::terminate();
    }
    std::string_view lineView(line);
    std::string_view point = lineView.substr(0, pos);
    // std::string point = line.substr(0, pos);
    checkThatPointIsValid(point);
    // std::cout << lineNumber << ": " << line << std::endl;
  }
}