Iterating through string C++ - 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.

Related

Does it matter where I initialize my integer?

I'm trying to understand something. I'm still a beginner to c++ and I just created this little program where you input a value and it tells you whether it's even or odd. To do this, I made an integer called "result" which takes value, and then does % 2 operation.
However, my first mistake was that I put int result above "cin >> value" so for some reason that messed up the program and the number would always be even no matter what. Then when I put int result below "cin >> value" the program worked like it should. Why is it doing this?
Any help would be appreciated thank you. I apologize if this is a duplicate but I don't know what to search for.
#include <iostream>
#include <string>
#include "Human.h"
#include <ctime>
using namespace std;
int main() {
int value = 0; // where I input
cin >> value;
// if you put int result above cin program changes.
int result = value % 2;
if (result == 0) {
cout << "Even number." << endl;
}
else {
cout << "Odd number." << endl;
}
return 0;
}
Any code whichever programming language you use runs from top to bottom.
You need to first declare the variable, give it a value and then check for being even or odd.
When you used cin after setting the value of result = value%2; the compiler used the originally initialized value for value which is 0 to compute the value of result which will be 0%2.
That's why you need to use cin>>value; before setting result = value%2;.
C++ read the code top to bottom , line by line. So you will have to int your variable first.I made a much more simpler version of the program if you want to read it:
#include <iostream>
using namespace std;
int main() {
int a;
cout << "a=";
cin >> a ;
if(a%2==0)
{cout<<"a is even";}
else
{cout<<"a is uneven";}
}
When you put int result = value % 2; before cin >> value;, your program will calculate the result before you put a value inside int value via your input.
So your program does calculate int result = 0 % 2;

Super basic code: Why is my loop not breaking?

for(int i=0;i<50;i++,size++)
{
cin >> inputnum[i];
cout << size;
if(inputnum[i] == '.')
{
break;
}
}
The break breaks the input stream but the size keeps outputting.
The output of size is 012345678910111213...474849.
I tried putting size++ inside the loop but it made no difference. And size afterwards will be equal to 50, which means it went through the full loop.
I forgot to explain that I added the cout << size within the loop to debug/check why it outputted to 50 after the loop even if I only inputted 3 numbers.
I suspect that inputnum is an array of int (or some other numeric type). When you try to input '.', nothing actually goes into inputnum[i] - the cin >> inputnum[i] expression actually fails and puts cin into a failed state.
So, inputnum[i] is not changed when inputting a '.' character, and the break never gets executed.
Here's an slightly modified version of your code in a small, complete program that demonstrates using !cin.good() to break out of the input loop:
#include <iostream>
#include <ostream>
using namespace std;
int main()
{
int inputnum[50];
int size = 0;
for(int i=0;i<50;i++,size++)
{
cin >> inputnum[i];
if (!cin.good()) {
break;
}
}
cout << "size is " << size << endl;
cout << "And the results are:" << endl;
for (int i = 0; i < size; ++i) {
cout << "inputnum[" << i << "] == " << inputnum[i] << endl;
}
return 0;
}
This program will collect input into the inputnum[] array until it hits EOF or an invalid input.
What is inputnum ? Make sure t's a char[]!! with clang++ this compiles and works perfectly:
#include <iostream>
int main() {
int size = 0;
char inputnum[60];
for(int i=0;i<50;i++,size++) {
std::cin >> inputnum[i];
std::cout << size;
if(inputnum[i] == '.') {
break;
}
}
return 0;
}
(in my case with the following output:)
a
0a
1s
2d
3f
4g
5.
6Argento:Desktop marinos$
Your code seams OK as long as you're testing char against char in your loop and not something else.. Could it be that inputnum is some integral value ? if so, then your test clause will always evaluate to false unless inputnum matches the numerical value '.' is implicitly casted to..
EDIT
Apparently you are indeed trying to put char in a int[]. Try the following:
#include <iostream>
int main() {
using namespace std;
int size = 0;
int inputnum[50];
char inputchar[50];
for(int i=0;i<50;i++,size++) {
cin >> inputchar[i];
inputnum[i] = static_cast<int>(inputchar[i]); // or inputnum[i] = (int)inputchar[i];
cout << size << endl; // add a new line in the end
if(inputchar[i] == '.') break;
}
return 0;
}
Then again this is probably a lab assignment, in a real program I'd never code like this. Tat would depend on the requirements but I'd rather prefer using STL containers and algorithms or stringstreams. And if forced to work at a lower-level C-style, I'd try to figure out to what number '.' translates to (simply by int a = '.'; cout << a;`) and put that number directly in the test clause. Such code however might be simple but is also BAD in my opinion, it's unsafe, implementation specific and not really C++.

array displaying more results than normal

this is my code:
#include <iostream>
using namespace std;
int main()
{
char character;
int x;
cout << "Input a character: " ;
cin >> character;
x = int(character);
cout << "Its integer value is: " << x << endl;
int arr[7], i=0,j;
while(x>0)
{
arr[i]=x%2;
i++;
x=x/2;
}
cout << "Its Binary format is: ";
for (j=i; j>=0;j--)
{
cout<<arr[j];
}
return 0;
}
I have only 8 array spaces allocated for this code but the displayed result is more than 8 and is totally unrelated to the algorithm. I'm suspecting this to be an overflow issue.
How do i remedy this issue?
Thank you!
while(x>0)
{
arr[i]=x%2;
i++;
x=x/2;
}
let's take case when this loop is executed once.
i is 1 after loop is finished. However, array element at index 1 is not initialized.
You trigger undefined behaviour by trying to print it here:
for (j=i; j>=0;j--) // assuming for should be here
{
cout<<arr[j]; // access array element with index 1 (our example)
}
The fix is to change your loop to
for (j=i-1; j>=0;j--)
Also beware what if user enters number which is larger (or equal) than 7th power of 2. You won't have places in your array to store all digits. And will trigger again undefined behaviour, by trying to write past the end of the array.

Why do I get an out_of_range exception here?

Currently doing a project at uni where at first I need to de-hyphenate a string, seemed pretty simple however when i run the program it has an error WeirdPuncProgram.exe: Microsoft C++ exception: std::out_of_range at memory location 0x004EF898
It also is not returning the string value properly, inside the function answer() is changed and hyphens are removed but once it comes out its just the original input again.
#include <iostream>
#include <string>
using namespace std;
string answer;
string hyphonRemover(string answer)
{
string spacer = " ";
int h;
for (int i = 0; i < answer.length(); i++)
{
h = answer.find_first_of("-");
answer.replace(h, 1, spacer);
}
return answer;
}
int main()
{
cout << "Type a sentence which contains punctuation and ill remove it for you! " << endl << endl;
getline(cin, answer);
hyphonRemover(answer);
cout << answer << endl;
system("pause");
return 0;
}
every use of answer in hyphonRemover() will be local variable, not global answer you defined above.
thus the function will modify only its local variable.

console program exits [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to stop C++ console application from exiting immediately?
I have the following console program:
#include <iostream>
using namespace std;
int main()
{
int a;
int b;
cout<<"Enter a";
cin>>a;
cout<<"Enter b";
cin>>b;
int result = a*b;
cout<<"You entered"<<a<<"and you entered"<<b<<"Their product is"<<result<<endl;
return 0;
}
Once i run the program,it accepts the input but exits before i can have a look at the results.What do i need to do for the program not to exit before i can take a look at the results?.
BTW, you've already calculated the value of result before you've gotten your input for a and b, so the value of result will either be 0 if your compiler assembles code that zero-initializes any variables declared on the stack, or will just be some random value. In fact, you really don't need to even declare result ... you can calculate it's value in the cout statement. So you can adjust your last line so it looks like this:
cout << "You entered" << a <<"and you entered"<< b
<< "Their product is" << (a*b) << endl;
To stop the program from exiting, you can grab another char from stdin. So you can do the following:
cout << "Press any key to exit..." << endl;
char extra;
cin >> extra;
What about adding system ("pause"); before return 0; statement?
Use getche() ,getch() or any character based input function.
int main()
{
int a;
int b;
int result = a*b;
cout<<"Enter a";
cin>>a;
cout<<"Enter b";
cin>>b;
cout<<"You entered"<<a<<"and you entered"<<b<<"Their product is"<<result<<endl;
getch(); //use this.It would wait for a character to input.
return 0;
}
And generally we use Enter to exit the program whose ASCII value is fetched by it .But since it is of no use to us not storing it in a variable.
You could ask for more feedback
cout<<"You entered"<<a<<"and you entered"<<b<<"Their product is"<<result<<endl;
char stop;
cin >> stop;
I like to use getch() from conio.h when I'm on Windows, but that's not quite portable :/
Windows:
//1
system ("pause");
//2
#include<conio.h>
_getch();
.NET (Windows):
System::Console::ReadLine();
Overall:
#include <cstdlib.h>
return EXIT_SUCCESS;