Scanf in Objective C Crashes Xcode And the Program - objective-c

I have removed scanf from the code and the rest of the program runs with no issue. When the code reaches scanf, and after I type a number, xcode 'loses connection' and displays the error "Program ended with exit code: -1". I have also tried making 'input' an int, changed the name of variable input in case there was a conflict there, and tried it without fflush in the code. I am running Mountain Lion on Oracle VM Virtualbox, and my computer is on Windows 7, if that's relevant.
What am I doing wrong?
#import Foundation/Foundation.h
#include stdio.h
int main(int argc, const char * argv[])
{
#autoreleasepool {
float input = 1;
int i = 0;
float total = 0;
int max = 0;
int min = 1000;
while (input != 0){
NSLog(#"Please put in a number. \n");
scanf("%f", &input);
fflush(stdin);
if(input > max){
max = input;
}
if(input < min){
min = input;
}
total = total + input;
i++;
}
printf("The number of entered numbers was %i \n", i);
printf("The sum of the entered numbers is %f\n", total);
total = total/i;
printf("The average of all the numbers is %f\n", total);
printf("The highest number entered is %i\n", max);
printf("The lowest number entered is %i\n", min);
}
return 0;
}

fflush(stdin);
You probably want
fflush(stdout)
I'm not sure what fflush() will do with an FILE* opened for input.
This may or may not be the cause of your issues.

Return and Enter key have a different meaning inside Xcode. You go to the product menu and select build build for running and execute it in the terminal it will work fine.
Inside Xcode the Enter key in the numpad stops the program with a -1 return code. I am not sure whether this is bug or a feature, but I could not find the key in the keybinding for Xcode.
Please check here

Related

Why is my C program crashing after input?

I am learning to program in C and C++.
My C program keeps crashing after input, here's the code:
\#include\<stdio.h\>
main(){
int n, i,a,sum=0;
printf("How many numbers?\\n");
scanf("%d", &n);
for(i=0;i\<n;i++){
printf("What's the %d number\\n", i+1);
scanf("%d", &a);
sum=sum+a;
}
printf("Sum is %d", sum);
}
And here's the output from my compile log
Compiler: Default compiler
Executing gcc.exe...
gcc.exe "C:\\Dev-Cpp\\Reee.c" -o "C:\\Dev-Cpp\\Reee.exe" -I"C:\\Dev-Cpp\\include" -L"C:\\Dev-Cpp\\lib"
Execution terminated
Compilation successful
There is 0 errors and 0 warnings.
If someone knows how to fix it I would be really thankful.
I tried to make a program that sums up all the numbers in a row. I expected a sum output but the program crashed after input. The program crashes after I input the last number in a row, where it should sum up all of them and output the sum.
I copied this program, added "void" to the main function
and changed the include statement like this ⬇️
everything worked just fine
#include <stdio.h>
void main()
{
int n, i, a, sum = 0;
printf("How many numbers?\\n");
scanf("%d", &n);
for (i = 0; i < n; i++)
{
printf("What's the %d number\\n", i + 1);
scanf("%d", &a);
sum = sum + a;
}
printf("Sum is %d", sum);
}
//output:
How many numbers?\n2
What's the 1 number\n4
What's the 2 number\n5
Sum is 9
you should use only one \ when you print somthing.

If else function....how to use return

#include <stdio.h>
#include <cs50.h>
int GetPositiveInt();
int main (void)
{
int min; /*variable to hold minutes*/
printf ("How many minutes does it take you to use a shower?");
scanf ("%d", &min);
int numbtl = min * 12; /*computes number of bottles*/
if (min > 0)
{
printf ("Taking a shower you use %d bottles of water", numbtl);
}
else
{
printf ("Please enter the positive number: \n");
scanf ("%d", &min);}
return min;
}
}
I've written this program but I've got some bug in else place.
Here is the text which I get trying to execute this program.
~/workspace/pset1/ $ make water
clang -ggdb3 -O0 -std=c11 -Wall -Werror -Wshadow water.c -lcs50 -lm -o water
~/workspace/pset1/ $ ./water
How many minutes does it take you to use a shower?0
Please enter the positive number:
10
~/workspace/pset1/ $
Let me explin what I mean by this code and its execution. This code is used to compute how many bottles of water you use while taking a shower. 1 minute of shower equals 12 bottles.
If you enter the positive integer (for example, 10) the result will be like this:Taking a shower you use 120 bottles of water. BUT if you enter 0 or negative integer the program will ask you to enter the positive integer. And here is when the problem occurs. After entering the positive integer I get the result of 0 bottles.
Lets break down your program and see what it is doing; first
int GetPositiveInt();
Is a forward declaration for a function that is never used or defined, you can remove it entirely.
int main (void)
{
int min; /*variable to hold minutes*/
printf ("How many minutes does it take you to use a shower?");
scanf ("%d", &min);
Here we define the main function (the entry point to a c program) and declare a variable of type int called min. Then print out a line asking for user input and read in their response storing it in the min variable.
int numbtl = min * 12; /*computes number of bottles*/
Here you process min by multiplying it by 12 and storing the result in numbtl.
if (min > 0)
{
printf ("Taking a shower you use %d bottles of water", numbtl);
}
Here you check if min is valid, if it is you print the response. Here you can see the success path of your program is correct, the problem is what happens when min is not greater than 0. (Note there was a minor formatting error in this next bit that I corrected by what I assume you meant - note that this is why correct indenting and formatting is important).
else
{
printf ("Please enter the positive number: \n");
scanf ("%d", &min);
}
If min is not valid (ie less than or equal to 0) then you ask for another input and store it in min.
return min;
}
Lastly you return whatever is stored in min. Note you never actually do anything with this second value, except return it.
Side note: The return value on main is used as the exit status of your application. You can see the exit status of the last command in bash with echo $?.
$ ./water
How many minutes does it take you to use a shower?
2
Taking a shower you use 24 bottles of water
$ echo $?
2
This is probably not what you want. The exit status is normally 0 to indicate success and a positive number otherwise. This last return you will likely want return 0 to indicate your program has run successfully.
Now for the logic of your program, what it looks like you are trying to do is obtain some input from the user; validate it (obtaining new input if its invalid); then process it. So the first thing to do is move your processing to the end of your program
int main (void)
{
int min; /*variable to hold minutes*/
...
int numbtl = min * 12; /*computes number of bottles*/
printf ("Taking a shower you use %d bottles of water", numbtl);
return 0;
}
Now we just need to acquire and validate the user input; a typical algorithm to do this is:
prompt for user input
while (input is not valid) {
reprompt for user input
}
process user input
Converting this to c your applications ends up with;
int main (void)
{
int min; /*variable to hold minutes*/
printf ("How many minutes does it take you to use a shower? ");
scanf ("%d", &min);
while (min <= 0)
{
printf ("Please enter the positive number: ");
scanf ("%d", &min);
}
int numbtl = min * 12; /*computes number of bottles*/
printf ("Taking a shower you use %d bottles of water", numbtl);
return 0;
}
This will continue to ask the user for a positive number until they either enter one or hit crtl+c to kill the command. Once a valid number has been obtained it will processes it and print out the result.
#include <stdio.h>
#include <string.h>
int main (void)
{
long min;
char msg[255];
strcpy(msg,"How many minutes does it take you to use a shower?\n");
do {
printf ("%s", msg);
scanf ("%lu", &min);
strcpy(msg , "Please enter the positive number: \n");
}while( min <= 0 );
long numbtl = min * 12; /*computes number of bottles*/
printf ("Taking a shower you use %lu bottles of water", numbtl);
return 0;
}
You can also use a goto label. Here I used a goto label named start. If a number less than zero is entered then the program goes to beginning of the program. Hope, It helps.
#include<stdio.h>
int main (void)
{
int min; /*variable to hold minutes*/
start :
printf ("How many minutes does it take you to use a shower?\nEnter here : ");
scanf ("%d", &min);
if (min <= 0)
{
printf("Enter a number grater than zero\n\n");
goto start;
}
int numbtl = min * 12; /*computes number of bottles*/
printf ("Taking a shower you use %d bottles of water", numbtl);
return 0;
}

Java: Ask user input and divide by those integers

In Java,I need to ask user input for two integers. The program needs to divide by these two integers and produce a decimal to the sixth place.
I know that i will need to name two integers: numerator and denominator. Also, I need to name a double variable: result.
Thanks for the help!!
You haven't given any clues as to the language or platform you are using, but here is a basic example written in C running on a console.
#include <stdio.h>
int main()
{
int num, den;
double quo;
printf("Enter numerator: ");
scanf("%d", &num);
printf("Enter denominator: ");
scanf("%d", &den);
if (den == 0)
printf("Divide by zero\n");
else {
quo = (double)num / (double) den;
printf("Quotient = %.6f\n", quo);
}
return 0;
}

Stange behavior with my C string reverse function

I'm just an amateur programmer...
And when reading, for the second time, and more than two years apart, kochan's "Programming in Objective-C", now the 6th ed., reaching the pointer chapter i tried to revive the old days when i started programming with C...
So, i tried to program a reverse C string function, using char pointers...
At the end i got the desired result, but... got also a very strange behavior, i cannot explain with my little programming experience...
First the code:
This is a .m file,
#import <Foundation/Foundation.h>
#import "*pathToFolder*/NSPrint.m"
int main(int argc, char const *argv[])
{
#autoreleasepool
{
char * reverseString(char * str);
char *ch;
if (argc < 2)
{
NSPrint(#"No word typed in the command line!");
return 1;
}
NSPrint(#"Reversing arguments:");
for (int i = 1; argv[i]; i++)
{
ch = reverseString(argv[i]);
printf("%s\n", ch);
//NSPrint(#"%s - %s", argv[i], ch);
}
}
return 0;
}
char * reverseString(char * str)
{
int size = 0;
for ( ; *(str + size) != '\0'; size++) ;
//printf("Size: %i\n", size);
char result[size + 1];
int i = 0;
for (size-- ; size >= 0; size--, i++)
{
result[i] = *(str + size);
//printf("%c, %c\n", result[i], *(str + size));
}
result[i] = '\0';
//printf("result location: %lu\n", result);
//printf("%s\n", result);
return result;
}
Second some notes:
This code is compiled in a MacBook Pro, with MAC OS X Maverick, with CLANG (clang -fobjc-arc $file_name -o $file_name_base)
That NSPrint is just a wrapper for printf to print a NSString constructed with stringWithFormat:arguments:
And third the strange behavior:
If I uncomment all those commented printf declarations, everything work just fine, i.e., all printf functions print what they have to print, including the last printf inside main function.
If I uncomment one, and just one, randomly chosen, of those comment printf functions, again everything work just fine, and I got the correct printf results, including the last printf inside main function.
If I leave all those commented printf functions as they are, I GOT ONLY BLANK LINES with the last printf inside main block, and one black line for each argument passed...
Worst, if I use that NSPrint function inside main, instead of the printf one, I get the desired result :!
Can anyone bring some light here please :)
You're returning a local array, that goes out of scope as the function exits. Dereferencing that memory causes undefined behavior.
You are returning a pointer to a local variable of the function that was called. When that function returns, the memory for the local variable becomes invalid, and the pointer returned is rubbish.

Scanning of the variables

I use a LINUX os and GCC complier. When I run this code,
#include<stdio.h>
int main()
{
int age;
char col;
printf("Enter a age ");
scanf("%d",&age);
printf("Enter a college:");
scanf("%c",&col);
if(age>=25 && (col=='H' || col=='Y'))
printf("Harvard");
else
printf("Yale");
return 0;
}
When I run this code, The output is ,
$./a.out
$Enter a age 28
Enter a college:Yale
$
Even when I tried giving different values to the age ,The output is still same.
Why does the loop aborts and prints the next statement in the code?
And When I change the variable declaration i.e, I first read the character and then the age ..Now the code is working normally.
Why does that happened?
After taking the integer input age, yo press enter and that should be count as a char, which assigns in col. You need to take care of that enter you've pressed using a getchar(). Look the code below:
int main(){
int age;
char col;
printf("Enter a age ");
scanf("%d",&age);
getchar(); // the enter which you hit after taking age as an integer input
printf("Enter a college:");
scanf("%c",&col);
if(age>=25 && (col=='H' || col=='Y'))
printf("Harvard");
else
printf("Yale");
return 0;
}