+ 1
In the following codes, program 2 works. But program 1 doesn't work. Why?
https://code.sololearn.com/c9QrdDOcoGDu/?ref=app https://code.sololearn.com/c9yh402cJrmX/?ref=app
3 Antworten
+ 3
std::string::at will never return '\0' because it will throw a runtime error if you try to access an index greater than (the length of the string - 1).
In "prg 1", when `i` reaches the value of 3, the loop condition is checked
a.at(3) != '\0'
as 3 is greater than (a.length() - 1), that is, as the 3rd index does not exist in the string, a runtime error is thrown.
To fix the program, change the loop condition to
while (i < a.length()) {...}
The compiler will give a warning saying that you are comparing integers of different signedness because `i` is a signed int whereas `a.length()` returns a long unsigned int. To fix that, simply change the data type of `i` to `unsigned int` or `size_t`(long unsigned int)
+ 1
Thank u xxx. Will you pls correct this code and send it.
+ 1
Also, why are including <string.h>, it is a C library. You need to include <string>.
https://code.sololearn.com/ckul1mADzOmP/?ref=app