Iterate over a C ++ string

I have a C ++ program where I need to iterate over a string and print characters. I get the correct output, but along with the output I get some garbage values ​​(garbage value is 0). I do not know why I get these values? Can anyone help me with this?

#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 Login

 hi 

Output

 hi0 
+5
source share
2 answers

The problem with this line is:

cout << number_needed(a) << endl;

Change it like this:

number_needed(a);

The problem is that number_needed() prints each letter of the string, but after that you print the value returned by number_needed() , which is 0.

+2
source

Your program behavior is undefined. number_needed is a void function, so for all program management paths, an explicit return value is required.

It's hard to know what you want to type cout in main . Judging by the text of your question, you can change the return type of number_needed to void and set main to

 int main(){ string a; cin >> a; number_needed(a); cout << endl; // print a newline and flush the buffer. return 0; } 
+5
source

Source: https://habr.com/ru/post/1272371/


All Articles