+ 1

No Numerals Chellenge , i can't pass the 3rd condition with this code

#include <iostream> #include <string> using namespace std; int main() { string input,word,output; getline(cin,input); for(int x = 0;input[x] != '\0';x++){ word += input[x]; if(input[x+1] == ' '||input[x+1] == '\0'){ if(word == "0"){ word = "zero"; } if(word == "1"){ word = "one"; } if(word == "2"){ word = "two"; } if(word == "3"){ word = "three"; } if(word == "4"){ word = "four"; } if(word == "5"){ word = "five"; } if(word == "6"){ word = "six"; } if(word == "7"){ word = "seven"; } if(word == "8"){ word = "eight"; } if(word == "9"){ word = "nine"; } if(word == "10"){ word = "ten"; } output += word + ' '; word = ""; x++; } } cout<<output; return 0; }

1st Apr 2021, 10:08 AM
umer assassin
umer assassin - avatar
3 Réponses
+ 2
There is a memory leak because you use input[x+1] != '\0' while adding x twice. Suppose you read the last character, which input[x+1] will be '\0'. What is done after changing the word makes the loop MIGHT NOT end because you do x++, making x added twice; one in the end of the loop, and one in the expression of for loop. input[x+2] is uninitialized and might not be zero, and even it is, which is likely in the other test cases. You should always avoid memory leak. There is a method length() in string class which get the length of the string, allowing you check x < input.length() instead.
1st Apr 2021, 11:09 AM
你知道規則,我也是
你知道規則,我也是 - avatar
+ 6
Shahid Zia , please do NOT spam here, the link you posted has no relation to the question / post.
1st Apr 2021, 10:19 AM
Lothar
Lothar - avatar
+ 5
CarrieForle Thanks 👍 - It is being addressed. Shahid Zia please quit spamming as this is being disrespectful to all community members. Please remove your spam comments everywhere you have placed them. Thanks - BroFar Gold Moderator
1st Apr 2021, 2:27 PM
BroFar
BroFar - avatar