Подтвердить что ты не робот

С++ std::string в boolean

В настоящее время я читаю файл ini с помощью пары ключ/значение. то есть.

isValid = true

При получении пары ключ/значение мне нужно преобразовать строку "true" в bool. Без использования boost, что было бы лучшим способом сделать это?

Я знаю, что я могу сравнить строку по значению ("true", "false"), но я хотел бы сделать преобразование, не имея в строке ini файла чувствительность к регистру.

Спасибо

4b9b3361

Ответ 1

Другим решением было бы использовать tolower(), чтобы получить строчную версию строки, а затем сравнить или использовать потоки строк:

#include <sstream>
#include <string>
#include <iomanip>
#include <algorithm>
#include <cctype>

bool to_bool(std::string str) {
    std::transform(str.begin(), str.end(), str.begin(), ::tolower);
    std::istringstream is(str);
    bool b;
    is >> std::boolalpha >> b;
    return b;
}

// ...
bool b = to_bool("tRuE");

Ответ 2

#include <string>
#include <strings.h>
#include <cstdlib>
#include <iostream>

bool
string2bool (const std::string & v)
{
    return !v.empty () &&
        (strcasecmp (v.c_str (), "true") == 0 ||
         atoi (v.c_str ()) != 0);
}

int
main ()
{
    std::string s;
    std::cout << "Please enter string: " << std::flush;
    std::cin >> s;
    std::cout << "This is " << (string2bool (s) ? "true" : "false") << std::endl;
}

Пример ввода и вывода:

$ ./test 
Please enter string: 0
This is false
$ ./test 
Please enter string: 1
This is true
$ ./test 
Please enter string: 3
This is true
$ ./test 
Please enter string: TRuE
This is true
$ 

Ответ 3

Если вы не можете использовать boost, попробуйте strcasecmp:

#include <cstring>

std::string value = "TrUe";

bool isTrue = (strcasecmp("true",value.c_str()) == 0);

Ответ 4

Опишите строку, итерации строки и вызова tolower на карахтерах, а затем сравните ее с "true" или "false", если ваша оболочка является вашей единственной проблемой.

for (std::string::iterator iter = myString.begin(); iter != myString.end(); iter++)
    *iter = tolower(*iter);