I have a c++ program where I need to iterate through a string and print the characters. I get the correct output but along with the output I get some garbage values(garbage value is 0). I don't know why i get those values? Can anyone help me with that?
#include <iostream>
using namespace std;
int number_needed(string a) {
for(int i=0;i<a.size();i++)
{
cout<<a[i];
}
}
int main(){
string a;
cin >> a;
cout << number_needed(a) << endl;
return 0;
}
sample Input
hi
Output
hi0
The behaviour of your program is undefined. number_needed
is a non-void
function so therefore it needs an explicit return
value on all program control paths.
It's difficult to know what you want the cout
in main
to print. Judging by your question text, you may as well change the return type of number_needed
to void
, and adjust main
to
int main(){
string a;
cin >> a;
number_needed(a);
cout << endl; // print a newline and flush the buffer.
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With