简体   繁体   English

C++:为什么我的字符串没有被打印?

[英]C++ : Why my string is not getting printed?

I am trying to convert time from 12 hour format to 24 hour format.我正在尝试将时间从 12 小时格式转换为 24 小时格式。 It is a hackerrank question which I am trying to solve.这是我试图解决的一个hackerrank问题。 Here is my code:-这是我的代码:-

#include <bits/stdc++.h>

using namespace std;

string timeConversion(string s) {
    string r;
    int hh,mm,ss;
    hh = (s[0]-'0')*10+(s[1]-'0');
    mm = (s[3]-'0')*10+(s[4]-'0');
    ss = (s[6]-'0')*10+(s[7]-'0');

    if(hh<12 && s[8] == 'P') hh +=12;
    if(hh == 12 && s[8]=='A') hh = 0;
    r[0]=hh/10+'0';
    r[1]=hh%10+'0';
    r[2]=':';
    r[3]=mm/10+'0';
    r[4]=mm%10+'0';
    r[5]=':';
    r[6]=ss/10+'0';
    r[7]=ss%10+'0';
    r[8]='\0';

    return r;
}

int main() {
    string s;
    cin >> s;
    string result = timeConversion(s);
    cout << result << endl;
    return 0;
}

This code is giving blank output.此代码给出空白输出。 Though when I cout result[0] then this gives me proper result.虽然当我计算结果 [0] 时,这会给我正确的结果。

See CppReference请参阅Cpp 参考

operator []运算符 []

No bounds checking is performed.不执行边界检查。 If pos > size() , the behavior is undefined.如果pos > size() ,则行为未定义。

When you define string r , its size() is zero, so all your character assignments are undefined behaviors.当您定义string r ,其size()为零,因此您的所有字符分配都是未定义的行为。 You may want to resize it first:您可能想先调整它的大小

r.resize(9);

Or alternatively, append the characters one-by-one:或者,一个一个地 附加字符

r = "";
r.push_back(hh/10+'0');
r.push_back(hh%10+'0');
r.push_back(':');
r.push_back(mm/10+'0');
r.push_back(mm%10+'0');
r.push_back(':');
r.push_back(ss/10+'0');
r.push_back(ss%10+'0');
// This isn't necessary
// r.push_back('\0');

Using operator+= makes your code look more natural:使用operator+=使您的代码看起来更自然:

r = "";
r += hh/10+'0';
r += hh%10+'0';
r += ':';
r += mm/10+'0';
r += mm%10+'0';
r += ':';
r += ss/10+'0';
r += ss%10+'0';
// This isn't necessary
// r += '\0';

Note you don't need the terminating zero because std::basic_string isn't null-terminated (it's not C-style string).请注意,您不需要终止零,因为std::basic_string不是空终止(它不是 C 样式字符串)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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