从变量输出字符串文字

时间:2018-06-20 17:11:59

标签: c++ c++11

我想知道是否可以从无法更改其值的预设变量输出原始字符串。例如:

string test = "test\ntest2";
cout << test;

将输出

test
test2

是否可以运行与上面类似的代码,但是更改cout语句以像这样打印原始字符串:

test\ntest2

2 个答案:

答案 0 :(得分:7)

转义序列\x仅转换为一个字符。

可能在某些平台上,终端字符打印为\n,但这完全取决于实现。

然后将其转换为两个字符(\x),这意味着您将不得不修改string本身。

最简单的方法是创建自定义函数。

void print_all(std::string s)
{
    for (char c : s) {
        switch (c) {
            case '\n' : std::cout << "\\n"; break;
            case '\t' : std::cout << "\\t"; break;

            // etc.. etc..

            default : std::cout << c;
        }
    }
}

对于您关心的所有escape sequences

注意:与ctrl-xx不同的是,{em}至少在ASCII表中\xx的值之间没有直接的相关性,因此必须使用switch语句。

答案 1 :(得分:2)

如果您使用的是c ++ 11,也可以使用原始字符串文字。

def multi_joueurs():
    global liste_des_joueurs
    liste_des_joueurs=[]

def  nombre_des_joueurs():
    fen2305=Tk()
    fen2305.title("un seul joueur")
    fen2305.config(bg='royalblue')
    label=Label(fen2305,text="nombre des joueurs dans ce matche:")
    global nobre_jouer
    nobre_joer=Entry(fen2305)
    botn=Button(fen2305,text="valider")
    label.grid()
    nobre_joer.grid()
    botn.grid()
    nobre_jouer=nobre_joer.get()
    ferme(fen2305)
    fen2305.mainloop()


def ouvre(m):
    fen23055=Tk()
    fen23055.title("un seul joueur")
    fen23055.config(bg='royalblue')
    label=Label(fen23055,text="donner le nom du joueur "+str(m)+":")
    nom_joueur=Entry(fen23055)

    label.grid()
    nom_joueur.grid()

    def va():
        global nom_pre_joueur
        nom_pre_joueur=nom_joueur.get()
        if nom_pre_joueur!='':
            fen23055.destroy()
    botn=Button(fen23055,text="valider",command=va)
    botn.grid()
    fen23055.mainloop()



def nom_des_joueurs():
    for m in range(int(eval(nobre_jouer))):
        ouvre(nobre_jouer)
        liste_des_joueurs.append(str(nom_pre_joueur))


nombre_des_joueurs()
nom_des_joueurs()

迈克