Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating through string C++

Tags:

c++

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
like image 259
Muthu Avatar asked Oct 05 '17 19:10

Muthu


1 Answers

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;
}
like image 179
Bathsheba Avatar answered Sep 29 '22 13:09

Bathsheba