1

Here's my code, also I don't want to change " this symbol.

#include <iostream>
#include <string>

using namespace std;
int main()
{
    string str = "-/"0123456789";
    cout << str;

    return 0;
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770

2 Answers2

4

You can either use an escape sequence for the quotation mark, i.e. replace it with ", or use a raw string literal. In a raw string literal, you enclose the string using R"( at the beginning, and )" at the end.

To illustrate:

#include <iostream>
#include <string>

using namespace std;
int main()
{
    string str1 = "-/\"0123456789"; //Escape sequence \"
    string str2 = R"(-/"0123456789)"; //Raw string literal
    cout << str1 << endl;
    cout << str2 << endl;

    return 0;
}
Marion
  • 198
  • 6
  • Thanks, and can i get raw string literal from a user? –  Dec 30 '21 at 16:25
  • 1
    How do you want to get it from the user? From standard input (i.e. terminal input)? Raw strings are relevant to written code, but unnecessary for data read from a file. So let's say you have code like: `string input; cin >> input; cout << input << endl;` If the user types in `-/"0123456789`, it will store this exactly in the string, and output it as such. – Marion Dec 30 '21 at 16:42
3

You need to escape with \ not /.

string str = "-\"0123456789";

-"0123456789

If you wanted to include the / then you can use string str = "-/\"0123456789";

-/"0123456789

In C++11 you can use a raw string

string str = R"(-"0123456789)"

-"0123456789

or string str = R"(-/"0123456789)"

-/"0123456789

yuuuu
  • 738
  • 3
  • 11
  • In your raw string examples, you are including more than 1 `"` in the literal data, so the output would actually be `"-"0123456789"` and `"-/"0123456789"`, respectively. To get the output the OP asked for, you need the raw literals to look like `R"(-"0123456789)"` and `R"(-/"0123456789)"` instead, respectively. – Remy Lebeau Dec 31 '21 at 07:43
  • You're right, my mistake. I've fixed it @RemyLebeau – yuuuu Dec 31 '21 at 08:05