Проблемы преобразования одной строки в другую

Я хочу преобразовать дату strVal = «1992-12-12» или «1992-9-9» формы в 19921212 & 19920909. Для этого я написал следующий фрагмент кода на C / C ++. Но проблема в том, что он преобразует 1992-12-12 в 1992012012. Кто-нибудь может подсказать мне, как показать, как исправить эту ошибку? У меня также могут быть входные данные в форме «1992-9», и я хотел бы преобразовать их в 19920900. Или «1992» в «19920000»

stringstream     collectTimeBegin;

for (string::iterator it = strVal.begin(); it != strVal.end(); )
{
if (*it != '-')
{
cout<< "\n -- *it=" << *it;
collectTimeBegin << *it;
it++;
}
else
{
stringstream    si("");
stringstream    sj("");
int             i;

it++;
si << *(it + 1);
sj<< *(it + 2);
i = atoi((si.str()).c_str()), j = atoi((sj.str()).c_str());
cout << "\n i=" << i << "\t j=" << j << "\n";
if ((i == 4) || (i == 5) || (i == 6) || (i == 7) || (i == 8) || (i == 9))
{
cout << "\n 1. *it=" << *it;
collectTimeBegin << *it;
it++;
}
else if ((j == 0) || (j == 1) || (j == 2) || (j == 3) || (j == 4) ||
(j == 5) || (j == 6) || (j == 7) || (j == 8) || (j == 9))
{
string     str = "0";

cout << "\n 2. *it=" << *it;
collectTimeBegin << str;
collectTimeBegin << *it;
it++;
}
}
}

0

Решение

Вот решение с использованием стандартного C ++; он использует тот же подход, что и у Кристиана: разделить ввод на основе тире, пропуская цифры на 0 с нулем:

#include <string>
#include <sstream>
#include <algorithm>

int main()
{
std::string date = "1992-9-12";

std::replace(date.begin(), date.end(), '-', ' ');   // "1992 9 12"
std::istringstream iss(date);
int year = 0, month = 0, day = 0;

if (iss.good()) iss >> year;    // 1992
if (iss.good()) iss >> month;   // 9
if (iss.good()) iss >> day;     // 12

std::ostringstream oss;
oss.fill('0');
oss.width(4); oss << year;
oss.width(2); oss << month;
oss.width(2); oss << day;
std::string convertedDate = oss.str();  // 19920912
}
3

Другие решения

если вы не возражаете против использования внешней библиотеки, я бы сделал это с boost.

    string input = "1992-9-9";
vector<string> v;
boost::algorithm::split(v, input, boost::algorithm::is_any_of("-"));
string output;
BOOST_FOREACH(const string &s, v)
{
if (s.size() == 1)
{
output += "0"+s;
} else {
output += s;
}
}
if (output.size() == 4)
output += "0000"if (output.size() == 6)
output += "00"

Редактировать: забыл обработать случай, если ваша входная строка длиной всего 6 или 4 цифры

1

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector