Post

stream

stringstream的几种用法

1. 字符串转数字

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <sstream>

int main() {
  std::string str = "123";
  int num;
  std::stringstream ss;
  ss << str;
  ss >> num;
  std::cout << ss.good() << std::endl;
  std::cout << num << std::endl;
  return 0;
}

2. 数字转字符串

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <sstream>

int main() {
  int num = 123;
  std::string str;
  std::stringstream ss;
  ss << num;
  if (ss >> str) {
    std::cout << str << std::endl;
  }

  ss << "asd";
  ss >> num;
  if (ss.eof() && !ss.fail()) {
    std::cout << num << std::endl;
  } else {
    std::cout << "error" << std::endl;
  }
  return 0;
}

3. 字符串转数组

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <sstream>
#include <string>
#include <vector>

int main() {
  std::string str = "1  ,2,  3   ,4  ,  5";
  str.erase(
      std::remove_if(str.begin(), str.end(), [](auto ch) { return ch == ' '; }),
      str.end());
  std::vector<int> vec;
  std::stringstream ss;
  ss << str;
  std::string substr;
  while (getline(ss, substr, ',')) {
    vec.push_back(std::stoi(substr));
  }
  for (auto i : vec)
    std::cout << i << std::endl;
  return 0;
}

4. 空格分隔的字符串转数组

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <sstream>
#include <vector>

int main() {
  std::string str = "1 2 3 4 5";
  std::vector<int> vec;
  std::stringstream ss;
  ss << str;
  for (int i; ss >> i;) {
    vec.push_back(i);
  }
  for (auto i : vec) std::cout << i << std::endl;
  return 0;
}
This post is licensed under CC BY 4.0 by the author.

Trending Tags