简体   繁体   中英

Iterating through string 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

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;
}

The problem is with this line:

cout << number_needed(a) << endl;

Change it to just:

number_needed(a);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM