# Search Results

• ### Query Regarding Character Operations..

##### - by RBA
Hi, Please explain the following piece of code.. printf("%c\n",0+'0'); --> returns 0 printf("%c\n",1+'0'); --> returns 1 printf("%c\n",0+'1'); --> returns 1 printf("%c\n",1+'1'); --> returns 2 Thanx.

• ### Question about InputMismatchException while using Scanner

##### - by aser
The question : Input file: customer’s account number, account balance at beginning of month, transaction type (withdrawal, deposit, interest), transaction amount Output: account number, beginning balance, ending balance, total interest paid, total amount deposited, number of deposits, total amount withdrawn, number of withdrawals package sentinel; import java.io.*; import java.util.*; public class Ex7 { /** * @param args the command line arguments */ public static void main(String[] args) throws FileNotFoundException { int AccountNum; double BeginningBalance; double TransactionAmount; int TransactionType; double AmountDeposited=0; int NumberOfDeposits=0; double InterestPaid=0.0; double AmountWithdrawn=0.0; int NumberOfWithdrawals=0; boolean found= false; Scanner inFile = new Scanner(new FileReader("Account.in")); PrintWriter outFile = new PrintWriter("Account.out"); AccountNum = inFile.nextInt(); BeginningBalance= inFile.nextDouble(); while (inFile.hasNext()) { TransactionAmount=inFile.nextDouble(); TransactionType=inFile.nextInt(); outFile.printf("Account Number: %d%n", AccountNum); outFile.printf("Beginning Balance: \$%.2f %n",BeginningBalance); outFile.printf("Ending Balance: \$%.2f %n",BeginningBalance); outFile.println(); switch (TransactionType) { case '1': // case 1 if we have a Deposite BeginningBalance = BeginningBalance + TransactionAmount; AmountDeposited = AmountDeposited + TransactionAmount; NumberOfDeposits++; outFile.printf("Amount Deposited: \$%.2f %n",AmountDeposited); outFile.printf("Number of Deposits: %d%n",NumberOfDeposits); outFile.println(); break; case '2':// case 2 if we have an Interest BeginningBalance = BeginningBalance + TransactionAmount; InterestPaid = InterestPaid + TransactionAmount; outFile.printf("Interest Paid: \$%.2f %n",InterestPaid); outFile.println(); break; case '3':// case 3 if we have a Withdraw BeginningBalance = BeginningBalance - TransactionAmount; AmountWithdrawn = AmountWithdrawn + TransactionAmount; NumberOfWithdrawals++; outFile.printf("Amount Withdrawn: \$%.2f %n",AmountWithdrawn); outFile.printf("Number of Withdrawals: %d%n",NumberOfWithdrawals); outFile.println(); break; default: System.out.println("Invalid transaction Tybe: " + TransactionType + TransactionAmount); } } inFile.close(); outFile.close(); } } But is gives me this : Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Scanner.java:840) at java.util.Scanner.next(Scanner.java:1461) at java.util.Scanner.nextInt(Scanner.java:2091) at java.util.Scanner.nextInt(Scanner.java:2050) at sentinel.Ex7.main(Ex7.java:36) Java Result: 1

• ### Help me with this java program

##### - by aser
The question : Input file: customer’s account number, account balance at beginning of month, transaction type (withdrawal, deposit, interest), transaction amount Output: account number, beginning balance, ending balance, total interest paid, total amount deposited, number of deposits, total amount withdrawn, number of withdrawals package sentinel; import java.io.*; import java.util.*; public class Ex7 { /** * @param args the command line arguments */ public static void main(String[] args) throws FileNotFoundException { int AccountNum; double BeginningBalance; double TransactionAmount; int TransactionType; double AmountDeposited=0; int NumberOfDeposits=0; double InterestPaid=0.0; double AmountWithdrawn=0.0; int NumberOfWithdrawals=0; boolean found= false; Scanner inFile = new Scanner(new FileReader("Account.in")); PrintWriter outFile = new PrintWriter("Account.out"); AccountNum = inFile.nextInt(); BeginningBalance= inFile.nextDouble(); while (inFile.hasNext()) { TransactionAmount=inFile.nextDouble(); TransactionType=inFile.nextInt(); outFile.printf("Account Number: %d%n", AccountNum); outFile.printf("Beginning Balance: \$%.2f %n",BeginningBalance); outFile.printf("Ending Balance: \$%.2f %n",BeginningBalance); outFile.println(); switch (TransactionType) { case '1': // case 1 if we have a Deposite BeginningBalance = BeginningBalance + TransactionAmount; AmountDeposited = AmountDeposited + TransactionAmount; NumberOfDeposits++; outFile.printf("Amount Deposited: \$%.2f %n",AmountDeposited); outFile.printf("Number of Deposits: %d%n",NumberOfDeposits); outFile.println(); break; case '2':// case 2 if we have an Interest BeginningBalance = BeginningBalance + TransactionAmount; InterestPaid = InterestPaid + TransactionAmount; outFile.printf("Interest Paid: \$%.2f %n",InterestPaid); outFile.println(); break; case '3':// case 3 if we have a Withdraw BeginningBalance = BeginningBalance - TransactionAmount; AmountWithdrawn = AmountWithdrawn + TransactionAmount; NumberOfWithdrawals++; outFile.printf("Amount Withdrawn: \$%.2f %n",AmountWithdrawn); outFile.printf("Number of Withdrawals: %d%n",NumberOfWithdrawals); outFile.println(); break; default: System.out.println("Invalid transaction Tybe: " + TransactionType + TransactionAmount); } } inFile.close(); outFile.close(); } } But is gives me this : Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Scanner.java:840) at java.util.Scanner.next(Scanner.java:1461) at java.util.Scanner.nextInt(Scanner.java:2091) at java.util.Scanner.nextInt(Scanner.java:2050) at sentinel.Ex7.main(Ex7.java:36) Java Result: 1

• ### What is user gcc's purpose in requesting code possibly like this?

##### - by James Morris
In the question between syntax, are there any equal function the user gcc is requesting only what I can imagine to be the following code: #include <stdio.h> #include <string.h> /* estimated magic values */ #define MAXFUNCS 8 #define MAXFUNCLEN 3 int the_mainp_compare_func(char** mainp) { char mainp0[MAXFUNCS][MAXFUNCLEN] = { 0 }; char mainp1[MAXFUNCS][MAXFUNCLEN] = { 0 }; char* psrc, *pdst; int i = 0; int func = 0; psrc = mainp[0]; printf("scanning mainp[0] for functions...\n"); while(*psrc) { if (*psrc == '\0') break; else if (*psrc == ',') ++psrc; else { mainp0[func][0] = *psrc++; if (*psrc == ',') { mainp0[func][1] = '\0'; psrc++; } else if (*psrc !='\0') { mainp0[func][1] = *psrc++; mainp0[func][2] = '\0'; } printf("function: '%s'\n", mainp0[func]); } ++func; } printf("\nscanning mainp[1] for functions...\n"); psrc = mainp[1]; func = 0; while(*psrc) { if (*psrc == '\0') break; else if (*psrc == ',') ++psrc; else { mainp1[func][0] = *psrc++; if (*psrc == ',') { mainp1[func][1] = '\0'; psrc++; } else if (*psrc !='\0') { mainp1[func][1] = *psrc++; mainp1[func][2] = '\0'; } printf("function: '%s'\n", mainp1[func]); } ++func; } printf("\ncomparing functions in '%s' with those in '%s'\n", mainp[0], mainp[1] ); int func2; func = 0; while (*mainp0[func] != '\0') { func2 = 0; while(*mainp1[func2] != '\0') { printf("comparing %s with %s\n", mainp0[func], mainp1[func2]); if (strcmp(mainp0[func], mainp1[func2++]) == 0) return 1; /* not sure what to return here */ } ++func; } /* no matches == failure */ return -1; /* not sure what to return on failure */ } int main(int argc, char** argv) { char* mainp[] = { "P,-Q,Q,-R", "R,A,P,B,F" }; if (the_mainp_compare_func(mainp) == 1) printf("a match was found, but I don't know what to do with it!\n"); else printf("no match found, and I'm none the wiser!\n"); return 0; } My question is, what is it's purpose?

• ### Why is my producer-consumer blocking?

##### - by User007
My code is here: http://pastebin.com/Fi3h0E0P Here is the output 0 Should we take order today (y or n): y Enter order number: 100 More customers (y or n): n Stop serving customers right now. Passing orders to cooker: There are total of 1 order(s) 1 Roger, waiter. I am processing order #100 The goal is waiter must take orders and then give them to the cook. The waiter has to wait cook finishes all pizza, deliver the pizza, and then take new orders. I asked how P-V work in my previous post here. I don't think it has anything to do with \n consuming? I tried all kinds of combination of wait(), but none work. Where did I make a mistake? The main part is here: //Producer process if(pid > 0) { while(1) { printf("0"); P(emptyShelf); // waiter as P finds no items on shelf; P(mutex); // has permission to use the shelf waiter_as_producer(); V(mutex); // cooker now can use the shelf V(orderOnShelf); // cooker now can pickup orders wait(); printf("2"); P(pizzaOnShelf); P(mutex); waiter_as_consumer(); V(mutex); V(emptyShelf); printf("3 "); } } if(pid == 0) { while(1) { printf("1"); P(orderOnShelf); // make sure there is an order on shelf P(mutex); //permission to work cooker_as_consumer(); // take order and put pizza on shelf printf("return from cooker"); V(mutex); //release permission printf("just released perm"); V(pizzaOnShelf); // pizza is now on shelf printf("after"); wait(); printf("4"); } } So I imagine this is the execution path: enter waiter_as_producer, then go to child process (cooker), then transfer the control back to parent, finish waiter_as_consumer, switch back to child. The two waits switch back to parent (like I said I tried all possible wait() combination...).

• ### Indexing with pointer C/C++

##### - by Leavenotrace
Hey I'm trying to write a program to carry out newtons method and find the roots of the equation exp(-x)-(x^2)+3. It works in so far as finding the root, but I also want it to print out the root after each iteration but I can't get it to work, Could anyone point out my mistake I think its something to do with my indexing? Thanks a million :) #include <stdio.h> #include <math.h> #include <malloc.h> //Define Functions: double evalf(double x) { double answer=exp(-x)-(x*x)+3; return(answer); } double evalfprime(double x) { double answer=-exp(-x)-2*x; return(answer); } double *newton(double initialrt,double accuracy,double *data) { double root[102]; data=root; int maxit = 0; root[0] = initialrt; for (int i=1;i<102;i++) { *(data+i)=*(data+i-1)-evalf(*(data+i-1))/evalfprime(*(data+i-1)); if(fabs(*(data+i)-*(data+i-1))<accuracy) { maxit=i; break; } maxit=i; } if((maxit+1==102)&&(fabs(*(data+maxit)-*(data+maxit-1))>accuracy)) { printf("\nMax iteration reached, method terminated"); } else { printf("\nMethod successful"); printf("\nNumber of iterations: %d\nRoot Estimate: %lf\n",maxit+1,*(data+maxit)); } return(data); } int main() { double root,accuracy; double *data=(double*)malloc(sizeof(double)*102); printf("NEWTONS METHOD PROGRAMME:\nEquation: f(x)=exp(-x)-x^2+3=0\nMax No iterations=100\n\nEnter initial root estimate\n>> "); scanf("%lf",&root); _flushall(); printf("\nEnter accuracy required:\n>>"); scanf("%lf",&accuracy); *data= *newton(root,accuracy,data); printf("Iteration Root Error\n "); printf("%d %lf \n", 0,*(data)); for(int i=1;i<102;i++) { printf("%d %5.5lf %5.5lf\n", i,*(data+i),*(data+i)-*(data+i-1)); if(*(data+i*sizeof(double))-*(data+i*sizeof(double)-1)==0) { break; } } getchar(); getchar(); free(data); return(0); }

• ### C: How come an array's address is equal to its value?

##### - by Alexandre
In the following bit of code, pointer values and pointer addresses differ as expected. But array values and addresses don't! How can this be? Output my_array = 0022FF00 &my_array = 0022FF00 pointer_to_array = 0022FF00 &pointer_to_array = 0022FEFC ... #include <stdio.h> int main() { char my_array[100] = "some cool string"; printf("my_array = %p\n", my_array); printf("&my_array = %p\n", &my_array); char *pointer_to_array = my_array; printf("pointer_to_array = %p\n", pointer_to_array); printf("&pointer_to_array = %p\n", &pointer_to_array); printf("Press ENTER to continue...\n"); getchar(); return 0; }

• ### Could anyone explain these undefined behaviors (i = i++ + ++i , i = i++, etc...)

##### - by PiX
int main(int argc, char ** argv) { int i = 0; i = i++ + ++i; printf("%d\n", i); // 3 i = 1; i = (i++); printf("%d\n", i); // 2 Should be 1, no ? volatile int u = 0; u = u++ + ++u; printf("%d\n", u); // 1 u = 1; u = (u++); printf("%d\n", u); // 2 Should also be one, no ? register int v = 0; v = v++ + ++v; printf("%d\n", v); // 3 (Should be the same as u ?) }

• ### Rle Encoding...What's the wrong?

##### - by FILIaS
I'm trying to make a Rle Encoder Programme.I read the way it works on notes on net. And i tried to fix my code! Regardless I think that the structure and logic of code are right,the code doesnt work! It appears some strange 'Z' as it runs. I really cant find what;s wrong! Could u please give me a piece of advice? Thanx in advance... #include <stdio.h> int main() { int count; unsigned char currChar,prevChar=EOF; while(currChar=getchar() != EOF) { if ( ( (currChar='A')&&(currChar='Z') ) || ( (currChar='a')&&(currChar='z') ) ) { printf("%c",currChar); if(prevChar==currChar) { count=0; currChar=getchar(); while(currChar!='EOF') { if (currChar==prevChar) count++; else { if(count<=9) printf("%d%c",count,prevChar); else { printf("%d%c",reverse(count),prevChar); } prevChar=currChar; break; } } } else prevChar=currChar; if(currChar=='EOF') { printf("%d",count); break; } } else { printf("Error Message:Only characters are accepted! Please try again! False input!"); break; } } return 0; } int reverse(int x) { int piliko,ypoloipo,r=0; x=(x<0)?-x:x; while (x>0) { ypoloipo=x%10; piliko=x/10; r=10*r+ypoloipo; x=piliko; } printf("%d",r); return 0; }

• ### Core Audio on iPhone - any way to change the microphone gain (either for speakerphone mic or headpho

##### - by Halle
After much searching the answer seems to be no, but I thought I'd ask here before giving up. For a project I'm working on that includes recording sound, the input levels sound a little quiet both when the route is external mic + speaker and when it's headphone mic + headphones. Does anyone know definitively whether it is possible to programmatically change mic gain levels on the iPhone in any part of Core Audio? If not, is it possible that I'm not really in "speakerphone" mode (with the external mic at least) but only think I am? Here is my audio session init code: OSStatus error = AudioSessionInitialize(NULL, NULL, audioQueueHelperInterruptionListener, r); [...some error checking of the OSStatus...] UInt32 category = kAudioSessionCategory_PlayAndRecord; // need to play out the speaker at full volume too so it is necessary to change default route below error = AudioSessionSetProperty(kAudioSessionProperty_AudioCategory, sizeof(category), &category); if (error) printf("couldn't set audio category!"); UInt32 doChangeDefaultRoute = 1; error = AudioSessionSetProperty (kAudioSessionProperty_OverrideCategoryDefaultToSpeaker, sizeof (doChangeDefaultRoute), &doChangeDefaultRoute); if (error) printf("couldn't change default route!"); error = AudioSessionAddPropertyListener(kAudioSessionProperty_AudioRouteChange, audioQueueHelperPropListener, r); if (error) printf("ERROR ADDING AUDIO SESSION PROP LISTENER! %d\n", (int)error); UInt32 inputAvailable = 0; UInt32 size = sizeof(inputAvailable); error = AudioSessionGetProperty(kAudioSessionProperty_AudioInputAvailable, &size, &inputAvailable); if (error) printf("ERROR GETTING INPUT AVAILABILITY! %d\n", (int)error); error = AudioSessionAddPropertyListener(kAudioSessionProperty_AudioInputAvailable, audioQueueHelperPropListener, r); if (error) printf("ERROR ADDING AUDIO SESSION PROP LISTENER! %d\n", (int)error); error = AudioSessionSetActive(true); if (error) printf("AudioSessionSetActive (true) failed"); Thanks very much for any pointers.

• ### objective-c 2.0 properties and 'retain'

Stupid question, but why do we need to use 'retain' when declaring a property? Doesn't it get retained anyway when it's assigned something? Looking at this example, it seems that an object is automatically retained when alloc'ed, so what's the point? #import "Fraction.h" #import <stdio.h> int main( int argc, const char *argv[] ) { Fraction *frac1 = [[Fraction alloc] init]; Fraction *frac2 = [[Fraction alloc] init]; // print current counts printf( "Fraction 1 retain count: %i\n", [frac1 retainCount] ); printf( "Fraction 2 retain count: %i\n", [frac2 retainCount] ); // increment them [frac1 retain]; // 2 [frac1 retain]; // 3 [frac2 retain]; // 2 // print current counts printf( "Fraction 1 retain count: %i\n", [frac1 retainCount] ); printf( "Fraction 2 retain count: %i\n", [frac2 retainCount] ); // decrement [frac1 release]; // 2 [frac2 release]; // 1 // print current counts printf( "Fraction 1 retain count: %i\n", [frac1 retainCount] ); printf( "Fraction 2 retain count: %i\n", [frac2 retainCount] ); // release them until they dealloc themselves [frac1 release]; // 1 [frac1 release]; // 0 [frac2 release]; // 0 ¦output Fraction 1 retain count: 1 Fraction 2 retain count: 1 Fraction 1 retain count: 3 Fraction 2 retain count: 2 Fraction 1 retain count: 2 Fraction 2 retain count: 1 Deallocing fraction Deallocing fraction This is driving me crazy!

• ### How to convert the date string into string( yyyy-MM-dd). While doing so, I getting null values ?

Hi, I have the data as customerFromDate " 01 Apr 2010 " and customerToDate " 30 Apr 2010 " which is a string. I want to convert that format into yyyy-MM-dd it should be in string. but while doing so. I got null values. Please see the following code which I had tried. printf("\n customerFromDate %s",[customerStatementObj.customerFromDate UTF8String]); printf("\n customerToDate %s",[customerStatementObj.customerToDate UTF8String]); /* prints as the following customerFromDate 01 Apr 2010 customerToDate 30 Apr 2010 */ NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init]; [dateFormatter setDateFormat:@"yyyy-MM-dd"]; NSDate *fromDate=[[NSDate alloc]init]; fromDate = [dateFormatter dateFromString:customerStatementObj.customerFromDate]; printf("\n fromDate: %s",[fromDate.description UTF8String]); NSString *fromDateString=[dateFormatter stringFromDate:fromDate]; printf("\n fromDateString: %s",[fromDateString UTF8String]); [dateFormatter release]; NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc]init]; [dateFormatter1 setDateFormat:@"yyyy-MM-dd"]; NSDate *toDate=[[NSDate alloc]init]; toDate = [dateFormatter1 dateFromString:customerStatementObj.customerToDate]; printf("\n toDate: %s",[toDate.description UTF8String]); NSString *toDateString=[dateFormatter1 stringFromDate:toDate]; printf("\n toDateString: %s",[toDateString UTF8String]); [dateFormatter1 release]; Thank you, Madan Mohan.

• ### C Programming Logic Error?

##### - by mbpluvr64
The following code compiles fine, but does not allow the user to choose whether or not the program is to run again. After giving the user the answer, the program automatically terminates. I placed the main code in a "do while" loop to have the ability to convert more than one time if I wanted too. I have tried to run the program in the command line (Mac and Ubuntu machines) and within XCode with the exact same results. Any assistance would be greatly appreciated. C Beginner P.S. Compiling on MacBookPro running Snow Leopard. #include <stdio.h> #include <stdlib.h> int main(void) { char anotherIteration = 'Y'; do { const float Centimeter = 2.54f; float inches = 0.0f; float result = 0.0f; // user prompt printf("\nEnter inches: "); scanf("%f", &inches); if (inches < 0) { printf("\nTry again. Enter a positive number.\n"); break; } else { // calculate result result = inches * Centimeter; } printf("%0.2f inches is %0.2f centimeters.\n", inches, result); // flush input fflush(stdin); // user prompt printf("\nWould you like to run the program again? (Y/N): "); scanf("%c", &anotherIteration); if ((anotherIteration != 'Y') || (anotherIteration != 'N')) { printf("\nEnter a Y or a N."); break; } } while(toupper(anotherIteration == 'Y')); printf("Program terminated.\n"); return 0; }

• ### What happens when we combine RAII and GOTO ?

##### - by Robert Gould
I'm wondering, for no other purpose than pure curiosity (because no one SHOULD EVER write code like this!) about how the behavior of RAII meshes with the use of Goto (lovely idea isn't it). class Two { public: ~Two() { printf("2,"); } }; class Ghost { public: ~Ghost() { printf(" BOO! "); } }; void foo() { { Two t; printf("1,"); goto JUMP; } Ghost g; JUMP: printf("3"); } int main() { foo(); } When running the following code in VS2005 I get the following output: 1,2,3 BOO! However I imagined, guessed, hoped that 'BOO!' wouldn't actually appear as the Ghost should have never been instantiated (IMHO, because I don't know the actual expected behavior of this code). Any Guru out there knows what's up? Just realized that if I instantiate an explicit constructor for Ghost the code doesn't compile... class Ghost { public: Ghost() { printf(" HAHAHA! "); } ~Ghost() { printf(" BOO! "); } }; Ah, the mystery ...

• ### Segmentation fault

##### - by darkie15
#include<stdio.h> #include<zlib.h> #include<unistd.h> #include<string.h> int main(int argc, char *argv[]) { char *path=NULL; size_t size; int index ; printf("\nArgument count is = %d", argc); printf ("\nThe 0th argument to the file is %s", argv[0]); path = getcwd(path, size); printf("\nThe current working directory is = %s", path); if (argc <= 1) { printf("\nUsage: ./output filename1 filename2 ..."); } else if (argc > 1) { for (index = 1; index <= argc;index++) { printf("\n File name entered is = %s", argv[index]); strcat(path,argv[index]); printf("\n The complete path of the file name is = %s", path); } } return 0; } In the above code, here is the output that I get while running the code: \$ ./output test.txt Argument count is = 2 The 0th argument to the file is ./output The current working directory is = /home/welcomeuser File name entered is = test.txt The complete path of the file name is = /home/welcomeusertest.txt Segmentation fault (core dumped) Can anyone please me understand why I am getting a core dumped error? Regards, darkie