loop on prompt with a yes or no? - objective-c

Good afternoon,
I'm trying to accomplish a task that i know should be doable. however my attempts seem to fail every time. My endeavor is to learn to code in Objective -c and have been making good progress. what i would like to do is add a loop to my current application that asks at the end if i would like to run again or some thing to that regard, and reply with a yes or no. if no the program ends and if yes it jumps back to the top of the project to start all over. kinda like what i have below? forgive me please if its not quite perfect, im still getting used to programing and am finding it incredibly fun.
#include <stdio.h>
int main(void)
{
char loop = yes;
while (loop = yes)
{
.
.
.
}
printf ("would you like to continue (yes/no)/n");
scanf ("%s", loop);
}

The printf and scanf need to be moved up inside the curly braces of the while loop. Also, you want \n instead of /n in the printf. Finally, you're going to get a string back with that scanf() call, so you'll want to declare loop as a char array, and then in the while loop, check the first element of that array for a 'y' or 'n' or something like that. You might also want to look at getchar() instead of scanf() for that sort of thing.

Not compiled here, but should work:
#include <stdio.h>
int main(void)
{
char buffer[256];
do {
.
.
.
printf ("would you like to continue (yes/no)/n");
scanf ("%s", buffer);
} while (strcmp(buffer,"yes") != 0);
}
One wouldn't do anything like that in a real world application, but for demonstration purpose it should be ok.
I made your variable an array, because strings are arrays of characters in C. Length is set to 256 bytes (255 characters + 0-byte as delimiter). I changed the loop to do-while to make it run at least once. For string comparison you need to call a function. strcmp returns 0 for identical strings. Finally, the question belongs in the loop.
It is plain C though, using nothing of Objective-C.

int main() {
char A = 'n';
char B = 'y';
char Answer;
printf("Does the subject have a glazed over look? (y/n): \n");
scanf("%c",&Answer);
if (Answer=='N'||Answer=='y'|| Answer=='N'||Answer=='Y')
printf("Good\n");
else
printf("Please enter 'y' or 'n' \n ");
return 0;
}

#include <stdio.h>
int main(void)
{
avi;
char loop[10];
while (loop = yes)
{
.
.
.
}
printf ("would you like to continue (yes/no)/n");
scanf ("%s", loop);
if(strcpm(loop,"YES")==0) goto avi:
}

Related

How to Avoid User String Inputs in Objective-C

My program asks for an integer input and I want to make sure (error trap) that the program would print "invalid" if the user inputs a string or any other character.
I'm new to Objective-C, hope you'll understand.
NSLog(#"1. Apple 2. Orange 3. Mango 4. Banana");
NSLog(#"Choose fruit:");
scanf("%d", &fruit);
**if(fruit>4 || fruit<1){
//If the user inputs any number other than the choices.
NSLog(#"Invalid.");
}
else if(...){
//if the user inputs a string or character
}**
I expecting the program would print "Invalid" if it would input a character or string or anything besides the choices.
Im not sure if you still require an answer . Im also fairly new so anyone feel free to add . Im not sure if this is meets your exact requirements but it does what you want it to . Instead of tryign to check for each and every data type what i suggest is check if the entered value is an integer or not . If it is do something else return the error message .Take a look at the below code .
int main(int argc, const char * argv[]) {
char str[50] = {0}; // init all to 0
NSLog(#"1. Apple 2. Orange 3. Mango 4. Banana");
NSLog(#"Choose fruit:"); // print buffer
scanf("%s",str);
// you can create an NS foundation NSString object from the str buffer
NSString *valueEntered = [NSString stringWithUTF8String:str];
if([valueEntered integerValue]){
printf("do somethinng here\n");
}
else{
printf("Not an integer\n");
}
}
First take the user's input as a NSString , so we can transfer it to a Integer value later onwards. The reason i have initialised it as a character is because Scanf wont allow to pass a String from what i read . So get the user's input as a character set change it to a String and check if it includes a Integer or not . IntegerValue returns the integer that the string holds if there is one , else it returns 0 .
Another method you can try is using ScanInt method in NSScanner. Issue with that is it will check if it includes a integer and return true . So something like "abc32" will also be true in that manner so probably wont be usefull for you .
Please let me know if this is what you expect as i also learnt a few things trying to solve this :)
Check the return value of scanf.
Having said that, using scanf for interactive input is often a recipe for confusion, so it might be a better idea to read input into a string with something like fgets and then analyze the string (possibly, but not necessarily, with sscanf).

Trying to check size of some cin statement

I have some simple user input function which reads what the user types, ignoring any enter's and taking the first character it comes across. I am using the cin.ignore statement because this is part of a menu, and I want to replay the menu if they enter none of the given options, but only once. Now I basically want to have an if-statement which is true iff the user entered only one character (he may enter multiple enter's before this character), so I wanted to use something like sizeof or length, but I couldn't quite get it to work. Can anybody help with this? It would be much appreciated. Also, if anything should be changed about the phrasing of the question, please let me know. Thanks in advance.
char Interface::leesin ( ) {
char invoer;
do {
invoer = cin.get();
} while (invoer == '\n');
cin.ignore(MAX,'\n');
return invoer;
}
the following is a code snippet whereby the user will be presented with a console menu and needs to input a character. The cin will read in only 1 char and then the program can do some processing with this char. The loop will terminate, when the user inputs the char '9'.
#include <iostream>
using namespace std;
int main() {
char ch;
do {
//print menu here
cin >> ch; // take in one char only
//perform action based on ch
} while (ch != '9');
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.

printf(), fprintf(), wprintf() and NSlog() won't print on XCode

I'm doing a small app for evaluating and analyzing transfer functions. As boring as the subject might seem to some, I want it to at least look extra cool and pro and awesome etc... So:
Step 1: Gimme teh coefficients! [A bunch of numbers]
Step 2: I'll write the polynomial with its superscripts. [The bunch of numbers in a string]
So, I write a little C parser to just print the polynomial with a decent format, for that I require a wchar_t string that I concatenate on the fly. After the string is complete I quickly try printing it on the console to check everything is ok and keep going. Easy right? Welp, I ain't that lucky...
wchar_t *polynomial_description( double *polyArray, char size, char var ){
wchar_t *descriptionString, temp[100];
int len, counter = 0;
SUPERSCRIPT superscript;
descriptionString = (wchar_t *) malloc(sizeof(wchar_t) * 2);
descriptionString[0] = '\0';
while( counter < size ){
superscript = polynomial_utilities_superscript( size - counter );
len = swprintf(temp, 100, L"%2.2f%c%c +", polyArray[counter], var, superscript);
printf("temp size: %d\n", len);
descriptionString = (wchar_t *) realloc(descriptionString, sizeof(wchar_t) * (wcslen(descriptionString) + len + 1) );
wcscat(descriptionString, temp);
counter++;
}
//fflush(stdout); //Already tried this
len = wprintf(L"%ls\n", descriptionString);
len = printf("%ls**\n", descriptionString);
len = fprintf(stdout, "%ls*\n", descriptionString);
len = printf("FFS!! Print something!");
return descriptionString;
}
During the run we can see temp size: 8 printed the expected number of times ONLY WHILE DEBUGGING, if I run the program I get an arbitrary number of prints each run. But after that, as the title states, wprintf, printf and fprintf don't print anything, yet len does change its size after each call.
In the caller function, (application:(UIApplication *)application didFinishLaunchingWithOptions:, while testing) I put an NSLog to print the return string, and I dont get ANYTHING not even the Log part.
What's happening? I'm at a complete loss.
Im on XCode 4.2 by the way.
What's the return value from printf/wprintf in the case where you think it's not printing anything? It should be returning either -1 in the case of a failure or 1 or more, since if successful, it should always print at least the newline character after the description string.
If it's returning 1 or more, is the newline getting printed? Have you tried piping the output of your program to a hex dumper such as hexdump -C or xxd(1)?
If it's returning -1, what is the value of errno?
If it turns out that printf is failing with the error EILSEQ, then what's quite likely happening is that your string contains some non-ASCII characters in it, since those cause wcstombs(3) to fail in the default C locale. In that case, the solution is to use setlocale(3) to switch into a UTF-8 locale when your program starts up:
int main(int argc, char **argv)
{
// Run "locale -a" in the Terminal to get a list of all valid locales
setlocale(LC_ALL, "en_US.UTF-8");
...
}

How do I get user input without using scanf in a console app?

I'm trying to allow users to simply hit Enter without typing anything, and use this to mean accepting a default value. scanf isn't doing what I want and the app still 'blocks': the next line of code doesn't run.
The only way is to actually type something THEN press Enter.
I tried using NSFileHandle and fileHandleWithStandardInput; however, it seems that the user is now forced to hit Ctrl-D to indicate EOF.
Someone suggested using fgets, but I cannot work out what to pass as 3rd parameter (of FILE* type). Tried stdin but it doesn't 'block'.
How do I accept input from a user, using Objective-C, and at the same time allow the user to simply hit Enter without being forced to type anything? How do I read a single line, even if that line is blank?
Assuming the code doesn't block and the next line runs immediately (as you seemed to indicate early in the question and in a comment), you have a common problem when mixing non-line-based and line-based input.
What happens is you have a newline left in the buffer, and fgets sees that, reads it, and returns, instead of doing what you really want: ignoring it, and then reading a line.
The solution is to simply do the ignoring part yourself, and then call fgets:
#include <stdio.h>
#include <string.h>
FILE* ignoreline(FILE* stream) {
for (int c; (c = fgetc(stream)) != EOF;) {
if (c == '\n') break;
}
return stream;
}
void example_use() {
char buf[1000];
ignoreline(stdin);
fgets(buf, sizeof buf, stdin);
// or, since it returns the stream, can be more compact:
fgets(buf, sizeof buf, ignoreline(stdin));
}
int main() { // error handling omitted
int n;
printf("Enter a number: ");
scanf("%d", &n);
char buf[1000];
printf("Enter a line: ");
ignoreline(stdin); // comment this line and compare the difference
fgets(buf, sizeof buf, stdin);
*strchr(buf, '\n') = '\0';
printf("You entered '%s'.\n", buf);
return 0;
}
Note that it is also common and encouraged to "pair" the ignoreline with the scanf (or other non-line-based input) to turn that into line-based input. You may want to modify it, in that case, so you can tell the difference between input of "42 abc" and "42" (in the "Enter a number" case). Some people just use fgets everywhere, then parse that line with sscanf, and while that works, it's not necessary.
I use getch(); in library conio.h
simply the program waits for any key to be pressed
If you're using Windows, you can use the ReadConsoleInput function (see MSDN for more on this) :
INPUT_RECORD keyin;
DWORD r;
while (ReadConsoleInput(GetStdHandle(STD_INPUT_HANDLE),&keyin,1,&r)) {
if (keyin.EventType!=KEY_EVENT) continue;
if (keyin.Event.KeyEvent.wVirtualKeyCode==VK_SPACE) break; ///use these VK codes to get any key's input
if (keyin.Event.KeyEvent.wVirtualKeyCode==VK_F1)
{
printf("You pressed F1\n");
}
if (keyin.Event.KeyEvent.wVirtualKeyCode==VK_F2)
{
printf("You pressed F2\n",);
}
}//end while loop
You don't need to hit enter after each key then.This works like a dream for me...
use getchar() to take input without using scanf function...