Monday, May 24, 2010

Can you help me debug this program? c++ updating a record, its error is in the search function?

#include "stdafx.h"


#include %26lt;stdio.h%26gt;


#include %26lt;stdlib.h%26gt;


#include %26lt;ctype.h%26gt;


#include %26lt;conio.h%26gt;


#include %26lt;string.h%26gt;





void searchNupdate();


void dispRec();


void displayRecord();


void displayTitle();


void updateRecord();


void search(int, int, int);





struct book


{


char bookID[6];


char title[31];


char author[31];


char copyright[5];


}bookrec;





FILE *bookfile;





int main()


{


bookfile= fopen("BOOK.DAT", "rb");





if(bookfile==NULL)


{


printf("File does not exist, press any key..");


getch();


}


else


{


fread(%26amp;bookrec, sizeof(bookrec), 1, bookfile);


if(feof(bookfile))


{


printf("File is empty, press any key..");


getch();


}


else


searchNupdate();


}


fclose (bookfile);





return 0;


}





void searchNupdate(void)


{


char rep;


int found=0;


int target=0;


int size;





displayTitle();


do


{


printf("Input book ID to be updated:");


scanf("%d", %26amp;target);





search(target,%26amp;found,size);





if(!found)


{


printf("Record is not found\n");


}


else


{


displayRecord();


}


do


{


printf("Update (Y/N)? :");


scanf("%c", %26amp;rep);


}


while(tolower(rep)!='y' %26amp;%26amp; tolower(rep)!='n');


if(rep=='y')


{


updateRecord();


}


do


{


printf("Update another (Y/N)? :");


fflush(stdin);


scanf("%c", %26amp;rep);


}while(tolower(rep)!='y' %26amp;%26amp; tolower(rep)!='n');


}


while(rep=='y');


fclose(bookfile);


}





void displayTitle(void)


{


printf("\n\t\t==UPDATE A FILE==\n");


printf("\t\t==BOOK==\n");


printf("UPDATE RECORDS:\n\n");


}





void dispRec(void)


{


printf("%s%s%s%s\n",bookrec.bookID,bo...


}





void displayRecord(void)


{


int lineCounter=0;





while(!feof(bookfile))


{


displayTitle();





while(lineCounter%26lt;10 %26amp;%26amp; !feof(bookfile))


{


dispRec();


lineCounter++;


fread(%26amp;bookrec, sizeof(bookrec), 1, bookfile);


}


if(!feof(bookfile))


{


printf("Press any key to continue..");


getch();


}


else


printf("End of file, press any key..");


getch();


}


}





void updateRecord(void)


{


char nBookid[6];


char nTitle[31];


char nAuthor[31];


char nCopyright[5];


int field;


char rep;





do


{


printf("Which field to update[1-4]? :");


scanf("%d", %26amp;field);





while(field%26gt;4)





if(field==1)


{


printf("Input new book ID:");


gets(nBookid);


}


else if(field==2)


{


printf("Input new book title:");


gets(nTitle);


}


else if(field==3)


{


printf("Input new book author:");


gets(nAuthor);


}


else


{


printf("Input new copyright:");


gets(nCopyright);


}





do


{


printf("Update another field(Y/N)? :");


scanf("%c", %26amp;rep);


}


while(tolower(rep)!='y' %26amp;%26amp; tolower(rep)!='n');





} while(rep=='y');





fseek(bookfile, 1, SEEK_SET);


fwrite(%26amp;bookrec, sizeof(bookrec), 1, (bookfile));


fclose(bookfile);


}





void search(int target[6], int found, int size)


{


int i;


int count=0;


int field=0;





bookfile= fopen("BOOK.DAT", "r+");


fread(%26amp;bookrec, sizeof(bookrec), 1, bookfile);





while(!feof(bookfile) %26amp;%26amp; found!=0)


{


if(target[i]==field)


{


found=1;


}


else


{


count++;


fread(%26amp;bookrec, sizeof(bookrec), 1, bookfile);


}


}


size= count * sizeof(%26amp;bookrec);


}

Can you help me debug this program? c++ updating a record, its error is in the search function?
i will try to help, email me and tell me whether or not you are trying to reverse engineer an already created program, if you are, i will not help, but if so, ill tell you what you need to do
Reply:what is that all about i did not understand any of the language
Reply:Search has conflicting parameter types.





It is declared as


void search(int, int, int);


but as implemented with:


void search(int target[6], int found, int size);





as you can see they are not the same. But I have no idea what some of the parameters are. The size paramater is useless, you don't even use it inside or outside of the function (if you plan to use it out of the function, change it to a reference to an int).





Your search function has way too many things wrong with it to work properly. Your variable i is uninitaliazed, so target[i] will just return junk. field is always 0, so target[i] is always compared with 0 (unless this is what you intended). found isnt a reference so it isnt useful outside of the function (as any changes to it applicable inside the function). bookfile is closed with fclose() (again unless you intended this). Sorry I can't be constructive in providing a solution, but I hate trying to decipher other people's code. But I hope these bring some problems out to light.





Also, the line -





while (tolower(rep)!='y' %26amp;%26amp; tolower(rep)!='n');





will always end up in a infinite loop if rep is 'y','Y','n',or 'N'. This is because rep never changes in the loop and so the statement is either always true or false. Try something like this.





while (tolower(rep)!='y' %26amp;%26amp; tolower(rep)!='n')


{


scanf("%c", %26amp;rep);


}

gardenia

Help with this c++ error?

When I run my program, I get these errors, even though I have I have added "#include %26lt;cmath%26gt;"!


Will anyone help me how to fix them, please!





thank you!





/usr/lib/gcc/i386-redhat-linux/4.1.1/.... no te: long double std::pow(long double, int)


/usr/lib/gcc/i386-redhat-linux/4.1.1/.... no te: float std::pow(float, int)


/usr/lib/gcc/i386-redhat-linux/4.1.1/.... no te: double std::pow(double, int)

Help with this c++ error?
The signature for pow() is:





double pow(double x, double y);





Change your second parameter from int to double. Changing your return variable to a double is also advisable.


.
Reply:Converting from float, double or long double to int sometimes causes problems. First I would suggest running the compiled program and see if it runs properly (in my experience, often the program will run just fine despite the compiler giving you a warning). If you're sure the program's behavior is actually bugged, then you'll have to find some way to convert between different variable types. Unfortunately I don't know exactly how this is done, I'm still a noob at C++.
Reply:#include%26lt;cmath%26gt;





//your function should be





{


double pow (double variable1, double variable2);


}





from


keng ping kong from www.iwohoo.com and www.pinkeikong.com


String to Int conversion in JAVA?

This is what I want to do. User enters a value accepted as a String in the format: d3 or 3d.Program checks if one of the two characters is 0-9, if it finds one that is 0-9 it converts it to an int and stores it. My other question is about the letter in the entry. For example with d3, I want to associate "d" with the integer 4. "a" is 1, "b" is 2 etc. If the user enters d3 or 3d I want the program to store 3 as an int, then store 4 as another int since "d" is the 4th letter in the alphabet. How do I do this, is there a method that I can use? If you know how to do it in C, C++ or JAVA(preferred) please tell me.

String to Int conversion in JAVA?
There is probably a better way, or at least a more streamline way, of doing this, but off the top of my head here is what I would do:





1. Create a loop to run through all the characters in your string.


2. Test each character to see if it falls between ASCII values 47 - 58 (i.e. 0-9). If it does then the character is a number.


3. If the first test fails then you know that it isn't a number; therefore, you know that it must be a character, so now test to see if it is a character between 'a' and 'd' (i.e. ASCII 97-100).





Here is some sample code (hopefully it can help):


public static void main(String[] args){


String teststr = "d3";


char x;





System.out.println("Test String:" + teststr);





for(int i = 0; i %26lt; teststr.length(); i++){


x = teststr.charAt(i);


if(x %26gt;= 47 %26amp;%26amp; x %26lt;= 58){


// Store it however


System.out.println(Integer.parseInt(""... x));


}


else if(x %26gt;= 97 %26amp;%26amp; x %26lt;= 100){


if(x == 'a')


System.out.println("a=" + 1);


else if(x == 'b')


System.out.println("b=" + 2);


else if(x == 'c')


System.out.println("c=" + 3);


else if(x == 'd')


System.out.println("d=" + 4);


}


}


}
Reply:How about using java.lang.Character?


String input = "3D";


for(int i = 0; i %26lt; input.length(); i++)


{


if(Character.isLetterOrDigit(


input.charAt(i)))


{


if(Character.isLetter(


input.charAt(i)))


{


column = input.toLowerCase().charAt(i) - 'a';


}


else


{


row = Integer.parseInt(


Character.toString(input.charAt(i)));


}


}


}
Reply:There can be multiple ways to do this... the one that I'd suggest is:


[this is based on the assumption that user enters only 2 chars]





1. From the input string, split the first char and second char and store them into separate Strings (you can do this by using substring).





2. Create a method that takes a string as an input and does the following:





private int getInt(String inStr) {





int outInt;


try {


outInt = Integer.parseInt(inStr);


} catch(NumberFormatException e) {


if(inStr=="a")


outInt = 1;


else if(inStr=="b")


outInt = 2;


else if(inStr=="c")


outInt = 3;


else if(inStr=="d")


outInt = 4;


}


return outInt;


}





What this method will do is - if the inStr is actually an int represented as String, it will return the corresponding int value, but if it actually is a char (rep as String), an exception will be thrown, which will be caught in catch and outInt will be set to appropriate value using the if blocks.





Hope this helps.
Reply:To convert a string to an integer you'll want to use the parseInt method of the Integer class:





String s = "100";


int i = Integer.parseInt(s.trim());





I would need to better understand the nature of the data users are entering and why they would enter it in the way you described to be able to comment on the other part of your question.


My program in C will not read past the decimal point for a double value?

Alright, here's the input file, basically.


2 200707211425 F70.5.


I read everything into a character array, except for after the F, I use a double. Problem is, when I print out the double, I only get 70, as opposed to 70.5. Take a look at the code, if you will.





int i;


for(i=0; i %26lt; SIZE; i++)


{








int z;


for (z = 0; z %26lt; 12; z++)


{





fscanf(sourceFile, "%c", %26amp;date[z]);





}





printDate(date);


fscanf(sourceFile, "%c", %26amp;discard);


fscanf(sourceFile, "%c1", %26amp;type[i]);


printf("%c", type[i]);


fscanf(sourceFile, "%d", %26amp;temp[i]);


printf("%d", temp[i]);





my temp value for the print (which is a double) only displays 70, when I need it to get 70.5.





Also, I have a loop to run a function that if type[i]=='F' (which it does), to do the function, and that isn't working either. Any ideas?

My program in C will not read past the decimal point for a double value?
If you are expecting the line





fscanf(sourceFile, "%d", %26amp;temp[i]);


printf("%d", temp[i]);





to read and print the F70.5 line, then you should change %d to %f. Please see http://www.cplusplus.com/reference/clibr...
Reply:%d is an integer format. use %f to read/print the float or %lf for the double precision float


In dev C++, when I debug my program and run it, why does it close after i put N an answer to 1 of my questions

I'm a beginner.





here's my code. can you correct it for me if it needs it? thanx








#include %26lt;iostream%26gt;


using namespace std;





int main()


{





int age;





cout%26lt;%26lt; "Hello Reader.\n"


%26lt;%26lt; "Welcome to my C++ program.\n";





cout %26lt;%26lt; "How old are you?";


cin %26gt;%26gt; age;





if (age %26lt;13)


cout %26lt;%26lt; "You are not yet a teenager.\n"


%26lt;%26lt; "Come back when you are older.\n";


else


cout %26lt;%26lt;"Welcome Teen!!\n";





int sex;





cout%26lt;%26lt;"Are you a girl or a boy?\n";


cin%26gt;%26gt; sex;





if (sex =boy)


cout %26lt;%26lt;"Your cool.\n";





else


cout %26lt;%26lt;"Your sexy.\n";


return 0;


endl;


}

In dev C++, when I debug my program and run it, why does it close after i put N an answer to 1 of my questions
The variable "sex" is not an integer; it is a string. Please change the variable type to "string" instead.





Second of all, you need quotes around "boy".





And third, you need to put == instead of =.





It should be:





#include %26lt;iostream%26gt;


#include %26lt;string%26gt;


using namespace std;





int main()


{





int age;





cout%26lt;%26lt; "Hello Reader.\n"


%26lt;%26lt; "Welcome to my C++ program.\n";





cout %26lt;%26lt; "How old are you?";


cin %26gt;%26gt; age;





if (age %26lt;13) {


cout %26lt;%26lt; "You are not yet a teenager.\n"


%26lt;%26lt; "Come back when you are older.\n";


}


else {


cout %26lt;%26lt;"Welcome Teen!!\n";


}








cout%26lt;%26lt;"Are you a girl or a boy?\n";


string sex;


getline(cin, sex);





if (sex == "boy") {


cout %26lt;%26lt;"Your cool.\n";


}


else {


cout %26lt;%26lt;"Your sexy.\n";


}


return 0;


}

aster

C-Programing: Writing a GPA calculator!?

I really suck at understanding the while loop, can anyone see whats wrong, i would like to write a gpa calculator as user inputs letters A,B,C,D,E,F it gives out the gpa!





Here is the code!





int main()


{ char x;


int num_grades;


float total;


printf("Please input grades (A,B,C,D or F) to calculate your GPA!\n");


scanf("%c",%26amp;x);


while (num_grades%26lt;=6)


{num_grades++;


switch (x)


{ case 'A':


total=total+4;


break;





case 'B':


total=total+3;


break;





case 'C':


total=total+2;


break;





case 'D': total=total+1;


break;





case 'F':


total=total+0;


break;





default:


printf("invalid input\n");


}


}


printf("Total number of grades inputed is

C-Programing: Writing a GPA calculator!?
There are a few issues with your code:





1. Uninitialized variables


2. scanf is outside the while loop.


3. not decrementing the count.


4. With scanf, you also have to read the rest of the input to eliminate chars until newline. So, if somebody entered 'Azx', then, you need to eliminate 'zx' and the newline.


Here is a suggestion:





#include %26lt;stdio.h%26gt;





int points[] = {4, 3, 2, 1,0};





int main()


{


char x = 'z';


char newline = 'z';


int num_grades = 0;


float total = 0.0;





while (x != 'Q')


{


printf("Enter grade (A,B,C,D or F) - Q to exit: ");


scanf("%c", %26amp;x);


/*


* Harvest and throw away the rest of the characters in the input


*/


while (newline != '\n')


{


scanf("%c", %26amp;newline);


}


newline = 'z';





x = (int) toupper(x);





if ((x%26gt;='A') %26amp;%26amp; (x%26lt;='F') %26amp;%26amp; (x!='E'))


{


num_grades++;


total = total + points[x-'A'];


}


else


{


if (x != 'Q')


printf("%c is invalid\n", x);


}


}





if (num_grades %26gt; 0)


{


printf("Number of grades: %d\n", num_grades);


printf("GPA : %.2f\n", total/num_grades);


}


return 0;


}
Reply:Can you add some more information on what is not working?


If you have to use switch, here's a mod. that shd work.





num_grades++;





switch (x)


{


case 'A':


total += 4;


break;


...


....


case 'Q':


num_grades--;


break;


default:


num_grades--;


printf("%c is invalid\n", x);


break;


} Report It

Reply:#include %26lt;iostream.h%26gt;





int main()


{


while(1){


char grade;


cout%26lt;%26lt;"Enter the grade for GPA value\n";


cin%26gt;%26gt;grade;


if(grade=='A' || grade=='a'){


cout%26lt;%26lt;"GPA value is 4\n";


}else if(grade=='B' || grade=='b'){


cout%26lt;%26lt;"GPA value is 3\n";


}else if(grade=='C' || grade=='c'){


cout%26lt;%26lt;"GPA value is 2\n";


}else if(grade=='D' || grade=='d'){


cout%26lt;%26lt;"GPA value is 1\n";


}else if(grade=='F' || grade=='f'){


cout%26lt;%26lt;"GPA value is 0\n";


}else{


cout%26lt;%26lt;"Wrong input\n";


}


}


return 0;


}
Reply:i can't read all of your code but there is some programming mistake u must initialize total,num_grades (i think both of must be zero at the declaration )
Reply:Looks like you're almost there... perhaps the end of your source was truncated?





Note that when you get an invalid input, you should subtract one from the num_grades - if not, you could produce incorrect results.





At the end, print out the number of grades input (num_grades) and then print the GPA which is the total divided by the number of grades.
Reply:KCNY1's answer is nice. It eliminates the tedious switch!
Reply:Your code assumes that num_grades and total automagically starts out as 0. It doesn't. You have to do that explicitly.





int num_grades = 0;


float total = 0.0;





Your while loop will probably never be executed because your uninitialized num_grades starts off as some big garbage number (greater than 6)





Once you get your while loop running, you can move ahead with fixing scanf. Decide whether you will have your user enter grades one at a time, or enter a list of grades. If one at a time, the user prompt and scanf should be inside your while loop. If you want them to enter a formatted list, you'll need to do some work to parse the list (find the significant letters and ignore spaces and commas, etc)





Good luck!


Modulus Problem In C++?

This is my program:





#include %26lt;cstdlib%26gt;


#include %26lt;iostream%26gt;


#include %26lt;math.h%26gt;


using namespace std;





int main(int argc, char *argv[])


{





double f = pow(123,17);


double c = fmod(f,3233) ;





cout%26lt;%26lt; f %26lt;%26lt; endl;


cout %26lt;%26lt; c %26lt;%26lt; endl;


system("PAUSE");


return EXIT_SUCCESS;


}





It works for smaller numbers (like if c = 8 mod 2 I will get 0), but if I have c = 123^17 mod 3233 I don't get 855 like I'm supposed to, I get 992. Any ideas why?

Modulus Problem In C++?
I think I know why it isn't working, but I don't yet know why you get 992. Doubles do not have as much precision as you need to perform that calculation . . . it's an integer calculation and the result of 123^17 is 337 587 917 446 653 715 596 592 958 817 679 803. It can depend on your system and your compiler, but according to Microsoft's interpretation of the double you have 7 or 15 digits of precision. The size of the double is something that's supposed to be standard, so that's probably the size you have to work with. Good night!
Reply:the simple reason your program is malfunctioning is due to the precision level of type double.





the number you are trying to check is some what very large for the memory to be hold so while truncating few value are omited.





if you use calculator to calculate,


123^17 mod 3233 = 885





but if you use the reverse way


i.e.


123^17/3233=Q


Q*3233+R( check once with 885, next time with 992)= both gives output "O"





if again you want to verify use the (output "O")^(1/17)=123.





hence its all due to holding of data in the memory by the computer using truncation.





Thanx BIBEK
Reply:Because you're operating on a float-type variable such as double!
Reply:The type double is not able to hold accuracy after so many precisions. This is true for all floating point numbers on computers. The reason lies in the representation of data in floats. Please read http://en.wikipedia.org/wiki/Floating_po...