首页 > 解决方案 > 如何打印字符串而不是数字

问题描述

我有一个叫做真值表的程序。如何打印“T”和“F”而不是 1 和 0?这是一些代码

string Choice, UserInput, NotChoice;
bool FirstChoice[2] = { true, false };
bool ValidInput = false;

bool InvertChoice = false;

cout<<"Enter a Hypothesis: ";
cin>>Choice;
do
{
    ValidInput = false;
    cout<<"Do you want to NOT "<<Choice<<"?(Y/N): ";
    cin>>UserInput;
    toUpper(UserInput);
    if (UserInput == "Y") 
    {   
        InvertChoice = true; ValidInput = true;
    }
    else if (UserInput == "N")
    {
        InvertChoice = false; ValidInput = true;
    }
    else
    {
        cout<<"ERROR: Please enter valid values [Y, N]" << endl;
    }
}
while (!ValidInput);

NotChoice = "~" + Choice;

cout<< Choice << (InvertChoice? " | ":"") <<(InvertChoice? NotChoice : "" )<<endl;

for ( int x = 0; x < 2; x++)
{
    bool FirstValue = InvertChoice ? !FirstChoice[x] : FirstChoice[x];
    for ( int z = 0; z < 1; z++ )
    {
        if ( InvertChoice == true )
        {
            cout<< setw(1) << FirstChoice[x] << " | " << FirstValue << endl;
        }
        else
        {
            cout<< setw(1) << FirstChoice[x] << endl;
        }
    }
}

我想这样打印

问 | ~问

T | F

F | 吨

这是实际的输出

问 | ~问

1 | 0

0 | 1

标签: c++

解决方案


您可以使用std::boolalpha打印“真”和“假”。

std::cout << std::boolalpha << true;

或者根据 bool 值选择一个字符串

bool x = true;
std::cout << (x ? "T" : "F");

推荐阅读