how to handle out of range?

apt list prints an extra field "[installed]" when a package is installed. however when package is not installed it omits the "[installed]\n" field from the record. how do a write this code to check if "[installed]\n" is the last field or not and if so return true, else return false.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
  bool isInstalled()
{
    string cmd = "apt list sysfsutils";
    cout << "cmd = " << cmd << endl;
    string apt_list = GetStdoutFromCommand(cmd).erase(0,11);
    cout << "apt_list = " << apt_list << endl;
    string installed = "[installed]\n";
    cout << "installed = " << installed << endl;
    
    size_t pos = (apt_list.find(installed);
    //when sysfsutils is not installed line looks like:
    //  sysfsutils/bionic,bionic-updates 2.1.0+repack-4build1 amd64
    //however when is Installed looks like:
    //  sysfsutils/bionic,bionic-updates 2.1.0+repack-4build1 amd64 [installed]
    
    cout << "pos = " << pos << endl;
    string token = (pos!=std::string::npos)?apt_list.substr():NULL;

    bool isInstalled = (token==installed)?true:false;
    cout << "isInstalled = " << isInstalled << endl;
    return isInstalled;
}


the actual print out is:
if installed:
Listing...
sysfsutils/bionic,bionic-updates 2.1.0+repack-4build1 amd64 [installed]
if not installed:
Listing...
sysfsutils/bionic,bionic-updates 2.1.0+repack-4build1 amd64

I tried to cut "Listing...\n" with erase()
Last edited on
> the actual print out is:
¿why there is no "cmd = ", "apt_list = ", or any other logging?

¿what's the problem with your code? ¿does it crash? ¿the result is wrong? ¿pure garbage?


> I tried to cut "Listing...\n" with erase()
use a debugger to see the actual content of your variables.
perhaps "Listing..." is produced by your command and send to the error stream

also, you may check if your strings do end with a '\n'


> bool isInstalled = (token==installed)?true:false;
may be simplified to bool isInstalled = token==installed;

> string token = (pos!=std::string::npos)?apt_list.substr():NULL;

string token; will give you an empty string
or token = ""; if you prefer
but token = NULL; is a great way of shooting your foot.
stop abusing ?:

and check the value of `token'
Last edited on
Ah Verdad! Grazie, huey! Me ayudo.
Registered users can post here. Sign in or register to post.