简体   繁体   中英

C++ store number in char using int variable

I need to be able to store number in char using variable and later able to detect if it is number or character for print, will try to explain with below's code sample:

#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<char> vChar;
    int testInt = 67;
    char testChar = 'x';
    char printChar;

    vChar.push_back(testInt);
    vChar.push_back(testChar);

    while (!vChar.empty()) {
        printChar = vChar.back();
        vChar.pop_back();
        cout << printChar << endl;
    }

    return 0;
}

Above code will output "x C", which is incorrect, because "cout" is printing "printChar" as char not as int and 67 is C in ASCII.

I could cast "int" over "printChar" but that would make it output "120 67", which is still incorrect. I have also tried to use conditions to detect which one is number, which one is character.

while (!vChar.empty()) {
    printChar = vChar.back();
    vChar.pop_back();
    if (isdigit(printChar)) {
        cout << int(printChar) << endl;
    }
    else {
        cout << printChar << endl;
    }
}

but "isdigit()" is never triggered and the result is same as without "int" cast...

How can I correctly print/output string for both numbers and characters using "char" type?

PS. I'm doing this for my school project to calculate matrixes, and using char for symbolicmatrixes is forced, thus I have to somehow be able to store both character and integer using char while differentiating them from each other.

How can I correctly print/output string for both numbers and characters using "char" type?

One option is store the additional information.

Instead of using

vector<char> vChar;

use

// The first of the pair indicates whether the stored value
// is meant to be used as an int.
vector<std::pair<bool, char>> vChar;

and then

vChar.push_back({true, testInt});
vChar.push_back({false, testChar});

while (!vChar.empty()) {
    auto printChar = vChar.back();
    vChar.pop_back();
    if ( printChar.first )
    {
       cout << (int)(printChar.second) << endl;
    }
    else
    {
       cout << printChar.second << endl;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM