0

Why too many charecters are printed ?!

Guys i have this problem plz help me #include <iostream> using namespace std; int main() { string a; cin>>a; char b=a[0]; for(int i=1; i<=b; i++){ cout<<a[0]; } return 0; } Suppose that i entered 567 , then i expect to print number 5 , 5 times . While it prints it too many times , why?

18th Feb 2021, 8:59 AM
Ali_combination
Ali_combination - avatar
2 Antworten
+ 2
when in " i<=b " i is compared with b , b value is casted to int type which is 53(ascii value) for character '5'. you should rather look into doing something like the following , int main() { string a; cin>>a; string c(1,a[0]); int b=stoi(c); for(int i=1; i<=b; i++){ cout<<a[0]; } return 0; } string constructor converts the above char a[0] to string first using "string c(1, a[0]) now you have a string "5" you can convert it to integer using "stoi" function. There are many other ways to convert character to string if above is confusing , so take a look at the article for better understanding of above method and various other ways. https://www.google.com/url?sa=t&source=web&rct=j&url=https://www.geeksforgeeks.org/how-to-convert-a-single-character-to-string-in-cpp/amp/&ved=2ahUKEwiIpcCMkPPuAhWfxTgGHW6lB4gQFjAAegQIBBAD&usg=AOvVaw1cQJIG9c_IEOhcI4-Mdvm5&ampcf=1
18th Feb 2021, 9:32 AM
Abhay
Abhay - avatar
+ 1
Abhay Thank you so much for making me aware of this point😊👍
18th Feb 2021, 11:14 AM
Ali_combination
Ali_combination - avatar