1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

C++でchar型をstring型に入れる方法

Last updated at Posted at 2020-02-24

#概要

  • char型をstring型に入れることができない
  • ostringstreamを使うと解決できる

#直接代入しちゃダメ
AtCoderで問題解いてるときにchar型をstring型に入れようとしたのですが、エラーが出てしまったので解決法を記します(他にいい方法は沢山ありそうですが)


#include <bits/stdc++.h>
using namespace std;

int main(){
    char c = 'a';
    string s = c;
    cout << s <<endl;
}

このコードだと以下のようなエラーが出てしまいます

hoge.cpp: In function 'int main()':
hoge.cpp:15:16: error: conversion from 'char' to non-scalar type 'std::string' {aka 'std::__cxx11::basic_string<char>'} requested
   15 |     string s = c;
      |                ^

#ostringstreamを使おう
ostringstreamを使うとこのような場合でも代入することができます


#include <bits/stdc++.h>
using namespace std;

int main(){
    char c = 'a';
    ostringstream oss;
    oss << c;
    string  s = oss.str();
    cout << s <<endl; 
}
1
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?