Why does it run again after finished main function

I am practicing C++. The task I am coding is below. It is just a simple task to save capital letters from a string. By setting breakpoints, I make sure that everything is running fine and output what I expected:

Input size=13
i=0
i=1
i=2
i=3
i=4
outputStr=A
i=5
outputStr=AU
i=6
outputStr=AUS
i=7
i=8
i=9
i=10
i=11
i=12
outputStr=AUS


But, after "return 0", it seems the "main" is running again, with empty input to the inputStr, then wrong "inputSize", previous output history is cleared and new output is :

Input size=0
i=0
i=1

...
...
...
i=2051

I am using Xcode. What's wrong?

------------------------------------------

#include <iostream>
#include <string>
using namespace std;

int main()
{
string inputStr,outputStr;
int inputSize;
// getline (cin, inputStr);
inputStr="9, AUStralia";
inputSize=inputStr.size();
cout<<"Input size="<<inputSize<<endl;

for (int i=0;i<=(inputSize-1);i++)
{
cout<<"i="<<i<<endl;
if (isupper(inputStr[i])==1)
{
outputStr=outputStr+inputStr[i];
cout<<"outputStr="<<outputStr<<endl;
}

}
cout<<"outputStr="<<outputStr<<endl;


return 0;
}
Last edited on
I don't know why you get the behaviour described. A minor point, the code you posted does not have a closing brace } after return 0;, but the compiler should report that as an error in any case.

By the way, you need to be careful when testing the return value of functions such as isupper(). The documentation states only that a non-zero value means 'true'. But it won't necessarily be equal to 1, it could be any integer other than zero.

It's safer to put:
 
    if (isupper(inputStr[i]))


... but this doesn't address the original question.

http://www.cplusplus.com/reference/cctype/isupper/
Return Value
A value different from zero (i.e., true) if indeed c is an uppercase alphabetic letter. Zero (i.e., false) otherwise.


there is } after return 0; (I have re-edited my codes)

It is so weird. Why does the main function is called again after once correctly run?

Thanks anyway,

L
I solved, but don't know why....

I go to Debug menu in Xcode, clicked "Clean", and then "Run" and it runs the main function once with expected output.

Not really sure how Xcode works. It seems I have to "Clean" and then "Run"

L
Topic archived. No new replies allowed.