string 사용

DONGJE LEE·2022년 8월 24일
0

C++

목록 보기
6/12
post-thumbnail

문자열에서 필요한 문장을 찾고, 자르고, 변환하는 방법.

  1. txt파일 열고 문장 한 줄씩 읽기
#include <iostream>
#include <fstream>
#include <string>
#include <vector>

int main(void){
  std::fstream file;
  std::string file_path = "읽을 파일 경로";
  std::vector<std::string> lines;
  std::string line;
  file.open(file_path, std::ios::in) // 읽기 모드
  if(!file.is_open()){
    std::cout << "error" << std::endl;
  }
  else{
    while(getline(file, line)){ // 파일에서 한 줄씩 읽어서
      lines.push_back(line); // 문자열 벡터에 push back
    }
  }
  file.close();
  return 0;
}
  1. 문장 찾기
lines[0].find("lat") // 못 찾으면 std::string::npos 반환
//찾으면 해당 문자열이 몇번째부터 시작인지 offset을 반환
  1. 문자열 자르기
std::string lat;
for(int i=0; i<lines.size(); i++){
  lat = lines[i].substr(lines[i].find("lat" + 5, 12);
} // substr함수로 해당 offset에서 문자 몇개를 자름 
  1. 문자열 변환
#include <iomanip>

std::stod("문자열"); // 문자열을 double로 변환
  1. 문자열 자르기
    std::string sample = "35.4824208, 129.3926115, 1663308948947947046";
    std::string lat, lon, time;
    lat = sample.substr(0, sample.find(","));
    sample.erase(0, sample.find(",") +2);
    lon = sample.substr(0, sample.find(","));
    sample.erase(0, sample.find(",") +2);
    time = sample.substr(0, sample.find("\n"));
result 
35.4824208
129.3926115
1663308948947947046
profile
LiDAR & SLAM & Robotics & Autonomous System

0개의 댓글