Monday, May 24, 2010

JAVA Making a CHAR equal a Number for an exercise creating GRADEBOOK. 2nd Post with CODE?

Possibly have MANY errors, but for now I'm concerned with the IF statement:


import javax.swing.*;


import java.lang.String;


import java.io.*; // This imports the File class


public class Lab10


{


public static void main (String args[])throws Exception


{


String StudentCountStr, SnameStr,Snumr,courseStr,lgradeStr,Grade...


Double nGrade;


FileWriter fw = new FileWriter("GradesTable.txt");


BufferedWriter bw = new BufferedWriter(fw);


PrintWriter pw = new PrintWriter(bw);


customerCountStr = JOptionPane.showInputDialog(null, "How many Customers to enter?");


StudentCountStr = JOptionPane.showInputDialog(null, "How many Student Grades to enter?");


/* Here the instructor will enter the number of students that must be entered.


Below, the string will be parsed to a numeric value for calculations */


SnameStr = JOptionPane.showInputDialog(null, "Enter Student Name");


Snumr = JOptionPane.showInputDialog(null, "Enter Student Number");


courseStr = JOptionPane.showInputDialog(null, "Enter Course Name %26amp; Section:");


lgradeStr = JOptionPane.showInputDialog(null, "Enter Letter grade: (no + or -");





// Grades are assigned as follows: A=4,B=3,C=2,D=1,F=0


Double GradeCount = Double.valueOf(GradeCountStr);





/* The syntax for the FOR loop is:


for(%26lt;initialization%26gt;; %26lt;condition%26gt;; %26lt;update%26gt;)


{ %26lt;executable statements%26gt; } */


for(int loopCount = 1; loopCount %26lt;= GradeCount; ++loopCount)





/* Here loopCount is initiated to 1 so as to never have a ZERO at the beginning. Then it is compared to


GradeCount. If loopCount is less than or equal to GradeCount, the program will go on %26amp; 1 will be added


to the value of loopcount. When loopCount is GREATER than GradeCount, the program will ask if there's


another student, if not it'll end.*/


{


if(lgradeStr.equals('A')) {nGrade = 4;}


else if (lgradeStr.equals(‘B’)) { nGrade = 3; }


else if (lgradeStr.equals(‘C’)) { nGrade = 2; }


else if (lgradeStr.equals(‘D’)) { nGrade = 1; }


else {ngrade = 0;}}


pw.println(" " + lgrade + " " + Gradepoints);


{


}


{


pw.println("Bucks County Community College Grade Report For");//this places the heading


pw.println(SnameStr);


pw.println(Snumr);


pw.println(" ");


pw.println(" ");


pw.println(" Course " + " Grade "+"Gradepoints");//This places the SubHeadings


}


pw.close();


}


}

JAVA Making a CHAR equal a Number for an exercise creating GRADEBOOK. 2nd Post with CODE?
This is quite simple, just use an if statement.





something like this:








char a = in.nextChar();


char b = 'b'


int i = (anything);


if(a == b)


{


i = 1;


}





and so on
Reply:I'm not to fmiliar with Java, but it sounds like you need to compare 2 strings (declare nGrade as a variable) to display 4 for A, 3 for B.... but that won't get you the GPA becaus eyou won't be able to ADD. Sorry


Accessing bits in C?

Say I have a bitfield like this:





typedef struct


{


unsigned char bit0:1;


unsigned char bit1:1;


unsigned char bit2:1;


unsigned char bit3:1;


unsigned char bit4:1;


unsigned char bit5:1;


unsigned char bit6:1;


unsigned char bit7:1;


}io_reg;





now I want to assign a unsigned char value to a io_reg type data so that I can access the bits of it. How can I do that? Please help me.

Accessing bits in C?
You can always create a union:





union {


unsigned char val;


typedef struct {


unsigned char bit0:1;


unsigned char bit1:1;


unsigned char bit2:1;


unsigned char bit3:1;


unsigned char bit4:1;


unsigned char bit5:1;


unsigned char bit6:1;


unsigned char bit7:1;


} bits;


} io_reg;





In this way, if you want to assign the entire unsigned char value, you can just use:





io_reg regUnion;


regUnion.val = value;





If you want to access the bits just do this:





regUnion.bits.bit0





etc.

survey for cash

Another C++ Question?

Sort and output an array of inputted characters, based on their number of occurrences (from highest to lowest). What's wrong with this code?





#include %26lt;iostream%26gt;


#include %26lt;fstream%26gt;





int main(void)


{


using namespace std;





char chars[]="abcdefghijklmnopqrstuvwxyz";


int i;


int count[]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0...





char inp;





cin%26gt;%26gt;inp;





while(inp !='.')


{


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


{


if(inp==chars[i])


count[i]++;


}


cin%26gt;%26gt;inp;


}





int swap;


char swapchar;





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


{


if (count[i] %26gt; count[i + 1])


{


swap = count[i];


count[i] = count[i + 1];


count[i + 1] = swap;





swapchar = chars[i];


chars[i] = chars[i + 1];


chars[i + 1] = swapchar;


}


}





cout%26lt;%26lt;"Character Count"%26lt;%26lt;endl;








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


{


if(count[i]!=0)


{


cout%26lt;%26lt;chars[i]%26lt;%26lt;" "%26lt;%26lt;count[i]%26lt;%26lt;endl;


}


}





system("pause");





return 0;


}

Another C++ Question?
You put your using statement inside main().
Reply:Well first of all your namespace position is incorrect... it should be after #include%26lt;fstream%26gt;, you don't need fstream since you are not doing any file streaming.





Second, check your braces... { and } i tried fixing your program and it doesnt work actually because of the errors... your swap or as we call it "Bubble sort" is ok... but change the limit from 26 to 25 since you'll be comparing the second to the last. Also, you'll have to put that in another loop since you need to do that 25 times again since you'll only be pushing one lowest number at a time... you should also try considering if there are equal times it appeared.





Note: I didn't fix it to work... i want you to handle that part. ^^, i'm just here to correct a few errors =)


Must allow for the char w to = 0?

When I test the code with 0000071w it reads false which is not correct. I then added the condition (letter == 0.) This is not correct. This code will give a false reading to all numbers?


%26lt;html%26gt;


%26lt;head%26gt;


%26lt;title%26gt; PPS Checksum %26lt;/title%26gt;


%26lt;/head%26gt;


%26lt;body%26gt;


%26lt;script type="text/javascript"%26gt;





var checknum=prompt("Please enter your PPS number","");


document.write("%26lt;br/%26gt; You entered " + checknum);


if(checknum!=null %26amp;%26amp; checknum!="")


{


var sum = 0;


for ( var i = 0; i %26lt; 7; i++)


{


var c = checknum.charCodeAt(i);


c = c- 48;


sum = sum + c *( 8-i);





}


checknum = checknum.toUpperCase();


letter = checknum.charCodeAt(7);


letter = letter - 64;


pos = sum % 23;


}





if ( pos == letter)||(letter== 0)





document.write("%26lt;br/%26gt; PPS number is valid");





else





document.write("%26lt;br/%26gt; PPS number is false");








%26lt;/script%26gt;


%26lt;/body%26gt;


%26lt;/html%26gt;

Must allow for the char w to = 0?
Hi


May I suggest you subtract (64 + 23) i.e. 87 from 'letter' not just 64 and remove the 'letter==0' from the if statement.


Hope this helps.


Regards


g


C++ "=" operator overloading?

I have following class, I want to overload “=” operator, I did as following but I cant get success, any one can help me please


class String


{


private:


char * name;


public:


const char * getName() const { }


void setName(const char * aname) { }


friend char * operator=(char %26amp; str, const String %26amp;rhs );


}





char * operator= (char %26amp;str, const String %26amp;rhs )


{


str = const_cast%26lt;char * %26gt;(rhs.getName())


return *str;


}





Void main()


{


String obj;


Obj.setName(“Hello World “);


Char * myString = Obj;


Cout%26lt;%26lt;myString;


}

C++ "=" operator overloading?
Sure.





Your problem here is that the parameters for your operator = are (char %26amp;, String %26amp;). You have two problems here.





First, you want to make that char *%26amp;, not char %26amp;. As defined here, you have an operator = that copies a string into a single character.





The second problem is a little bigger. You are copying a pointer here instead of doing any sort of copying of contents. When done, myString wand Obj will point at the SAME string.





While this makes for a very fast copy, you're almost guaranteed to have problems later:





1. Notice what happens to myString when Obj is deleted. myString is now pointing at deleted memory. The reverse is true as well.





2. If myString changes, so does Obj. The reverse is true as well.





3. There is no safe way to destroy the name * in your string object because you don't know how many copies were made, and if those are still in use. I'm assuming here that the implementation of setName() will allocate new memory for name, and that your full version has a destructor.





I hope this helps. Good luck.
Reply:You have completely mixed your metaphors here.





First off, your operator = only needs to take one parameter, not two -- and that parameter is whatever type you want to be able to assign TO your String.





Second, your operator = should return a String%26amp;.





Third, in order to assign a String object to a char*, you need to overload the char* cast operator.





And finally, make sure you understand that char* is just a pointer -- to actually put anything IN your string, you're going to have to dynamically allocate memory.


Need help with c-programming; strsr and other?

Write a function that takes as input a string containing HTML source code and returns both the # of images referenced in the code and the total screen area (in square pixels) occupied by the images


The function MUST have the following declarationint estImageContent(char *pacHTML, long int *pliArea);








1. Prompt the user for an input filename


2. Open the file, read its contents into a string (up to 20000 bytes), close file


3. Call estImageContent()


4. Print the following to the screen:


1. Input filename


2. Estimated # of images


3. Estimated total screen area in square pixels


5. Loop back to prompt





this is what i have so far


/* the first thing i did was uppercase*/





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


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


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








void fileToString(char filename[], char theString[]);


char *upperCaseTheString(char *pc);





int main()


{


char filename[] = "p6in1.txt";


char theString[20000] = "";





fileToString(filename, theString);


upperCaseTheString(theString);





printf("%s", theString);





return (0);


}








void fileToString(char filename[], char theString[]) {


FILE *fp;


char buf[BUFSIZ+1];





fp = fopen(filename, "r");





while (fgets(buf, BUFSIZ, fp) != NULL) {


strcat(theString, buf);


}





fclose(fp);





}








char *upperCaseTheString(char *pc) {


char *pcReturn = pc;





while (*pc != '\0') {


*pc = toupper(*pc);


pc++;


}





return pcReturn;


}


fp=fopen("p6in.txt","r");





if(fp==NULL)


{


printf("\n\t\tSORRY......\n\t\t CANNOT OPEN FILE\n");


return 0;


}





printf("\n\t\tFILE data.txt FOUND!\n");


printf("\n\nSearch what string?\t");


gets(str1);





while ((fgets( str2, 100, fp )) != NULL) //not the end of file


{


if (strcmp(str1, str2)


iCount++;











}


printf("\n%d OCCURRENCES OF STRING %s FOUND", iCount ,str1);








}

Need help with c-programming; strsr and other?
Here is a link with info about strstr:


http://www.cppreference.com/stdstring/st...
Reply:I don't know

customer satisfaction survey

C++ Question?

[code]


#include %26lt;iostream%26gt;


#include %26lt;fstream%26gt;


using namespace std;





int read ( char , char );





typedef struct


{


int computernum;


char fibit[8];


char sebit[8];


char thbit[8];


char fobit[8];





} address;





main ()


{


char red;


red = read (zero, one);





cout %26lt;%26lt; red %26lt;%26lt; endl;


return 0;


}





int read (char z, char o)


{


ifstream fin;


char zero;


char one;


fin.open ("prog2.dat");





if (fin.fail() )


{


cout %26lt;%26lt; "File not found or opened" %26lt;%26lt; endl;


exit(1);


}





if ( zero = 0)


{


zero= 0;


}


return 0;


}


[/code]





I am lost on the last part mostly. My instructor gave me a file named prog2.dat which contained this file





"


00001110011110010000101001011010


00000011000000110000011000000110


10010010001111110101101001010101


00000001000000010000000100000001


00000111001010111101010101110101


00000000101011110101010101110

C++ Question?
You haven't asked any question. All you've done is post some source code and input file info. What is the code supposed to do? What are you having trouble figuring out?
Reply:since int read(..) return only zero .....looks like your program will only output zeros....


so what is your question?


Which of the following string declarations contains an error?

a. char String1[3] = "xyz";


b. char String2[5] = "abcd";


c. char String4[ ] = "world"

Which of the following string declarations contains an error?
char String1[3]="xyz" is wrong. The correct declaration is char String1[4]="xyz"





Nelson Bittencourt


See my site:


http://www1.webng.com/nbittencourt/index...


Can someone pleaseeee tell me whats wrong with my code am stuckk....?

it supposed to calculate the amount due for the vehicle parked in a garage


the user enters type of car,hour arrival,minute arrival,exit hour,exit arrival then it supposed print it out in military time and charge and am not getting that any advices pleaseee thank youuu








import java.util.Scanner;


public class Assignment


{


public static void main(String [] args)


{


double hour = 0.0;


double minute = 0.0;


double cost = 0.0;


char C,c;


char V,v;





Scanner keyboard=new Scanner(System.in);


System.out.println("What kind of car do you have? C for car || V for van");





System.out.println("Enter arrival hour 0-23 ");


hour=keyboard.nextInt();





System.out.println("Enter arrival minute 0-59 ");


minute=keyboard.nextInt();





System.out.println("Enter exit hour ");


minute=keyboard.nextDouble();





System.out.println("Enter exit minute ");


minute=keyboard.nextDouble();





System.out.println("**************");


System.out.println("XXXXX");


System.out.println("**************");

Can someone pleaseeee tell me whats wrong with my code am stuckk....?
If I understand what you want properly, here is a program to complete what I think you want. Add more info if you need more help or if I misunderstood you.





// START OF CODE


import java.util.Scanner;


public class carvan


{


public static void main(String [] args)


{


// resulting values


double cost = 0.0;


boolean Van = false;


boolean Car = false;





// input data


double arrivalHours = 0.0;


double arrivalMinutes = 0.0;


double exitHours = 0.0;


double exitMinutes = 0.0;


String type; //type of vehicle





Scanner keyboard=new Scanner(System.in);


System.out.println("What kind of car do you have? C for car || V for van ");


type = keyboard.next();


if(type.charAt(0)=='C' || type.charAt(0)=='c')


Car = true;


else if(type.charAt(0)=='V' || type.charAt(0)=='v')


Van = true;





System.out.println("Enter arrival hour 0-23 ");


arrivalHours=keyboard.nextInt();





System.out.println("Enter arrival minute 0-59 ");


arrivalMinutes=keyboard.nextInt();





System.out.println("Enter exit hour ");


exitHours=keyboard.nextDouble();





System.out.println("Enter exit minute ");


exitMinutes=keyboard.nextDouble();





System.out.println("**************")...


System.out.println("XXXXX");


System.out.println("**************")...





double totalMins = ((exitHours*60.0)+exitMinutes) - ((arrivalHours*60.0)+arrivalMinutes); // find time stayed for





if( Van ) // for a van


{


if( totalMins %26gt;= 60.0*8.57 ) // if it is more than or = to 8.57 hours, the cost will be $30


cost = 30.0;


else // if parked for less than 8.57 hours


cost = 3.50 * Math.ceil(totalMins/60.0); // 3.50 per hour (and round hours up, ex 3:20 = 4 hours)


}


else if( Car ) // for a car


{


if( totalMins %26gt;= 60.0*10.0 ) // if parked for more than or = to 10 hours, the cost will be $20


cost = 20.0;


else // if parked for less than 10 hours


cost = 2.0 * Math.ceil(totalMins/60.0); // 2.00 per hour


}





System.out.printf("Parking a " + (Van?"van":"car") + " for %02d:%02d will cost $%.2f.", (int)Math.floor(totalMins/60), ((int)totalMins)%60, cost);


}


}


// END OF CODE


Please ask here if you need more help! ;P
Reply:Hello,


There is a lot wrong with this program, first the syntax is wrong. Then I am not sure the scope of your program but it should check for invalid data. Like what if I enter 53 for the hour? First get it to compile. Then you can test output and stuff.





If you can tell me exactly what you have to do, I can help you.
Reply:ahah
Reply:First, I don't think you fully grasp the concept of a char. Just as an int holds an integer and a double holds a decimal number, the char type holds characters. So, when declaring your instance variables you have written "char C, c;" and "char V, v;". Those two lines simply create variables to hold letters. Just like saying "double cost" creates a variable called "cost" that holds doubles, saying "char C" simply creates a variable called "C" that holds a character.





What this means, is that when you ask what kind of car the person has, you still need to use your Scanner to take in that char. Them simply typing a letter means nothing to your code.





Also, you made 4 char variables: C, c, v and V. I'm guessing you did this to account for case, that is, if the user types in C or c it will work. It was a noble attempt, but once again, chars don't work that way. So, what you should do is create a char variable called "car" or "vehicle", and create only one.





So replace your two lines that create char's with simply: char vehicle;.





Now, I noticed that when you ask the user what type of vehicle they have you use the "or" operator(||). Now, you could do this, but it's not necessary and most users won't know what that means. Remember, when you enclose something in double quotes ("") that's a string literal, so the computer won't read it, it will simply print it out. So a better question to ask your user is simply: "What kind of car do you have?(C for car or V for van)"





The next line of your code needs to assign the user input to your vehicle variable. So your next line of code should be this: vehicle = keyboard.nextChar();





Now the vehicle variable is holding the user input. So for now, we're good here.





Your next problem is that you assign multiple values to one variable, so only the last one shows.





Notice after you ask for arrival time, exit hour, and exit minute you assign the user input all to one variable. This won't work, because if you assign a value to a variable, it overwrites whatever was already there.





For example, let's say the user arrival minute was 27. They input 27 when prompted and 27 is assigned to the variable minute. Then when prompted they input 2 for exit hour. You have also assigned this value to the minute variable, which means that the 27 that was previously there, is overwritten! So you've lost that value. Then you do it again when asking for exit minute. The 2 that was stored in minute, is once again overwritten by the user input.





Don't worry though, this is a simple fix. Simply create 4 separate variables for arrival hour, arrival minute, exit hour, and exit minute.





So, replace "double hour" and "double minute" with this line of code: int arrivalHour, arrivalMinute, exitHour, exitMinute;





That line creates 4 int variables called arrivalHour, arrivalMinute, exitHour, and exitMinute.





Also, because these are int values, you must change your scanner to accept ints. So where you have written "keyboard.nextDouble();" you must write "keyboard.nextInt();".





Now you have 4 separate variables for arrival and exit time, and one char variable that represents car or van. We're doing well, but there's still more to be done with the rest of your code.





In this line: "double totalTime = (hour * 60.0) + minute;" you attempt to calculate the total number of minutes the user has been in the garage. Well, you have the right idea, but you aren't quite there.





How I would do this, is subtract the number of minutes past midnight that the user got there, from the number of minutes past midnight that the user left.





For instance, if the user arrived at 12:30 AM, and left at 1:45 AM, then the user arrived 30 minutes after midnight, and left 105 minutes after midnight. Therefore 105 - 30 would give you the number of minutes the user has been there.





This is easily done(oh and I'll be using int's instead of doubles since we're dealing with int's in the rest of your code: "int totalTime = (exitHour * 60 + exitMinute) - (arrivalHour * 60 + arrivalMinute);"





This code leaves us with the number of minutes the user has been there in the totalTime variable.





(We're not quite done here but I"m gonna post this to get you started and come back and finish it later)





edit:





Alright, almost done. You're next step is to check whether the vehicle is a car or a van. You had the right idea with your if statements, but you can't simply say if(van) without having a boolean variable called van.





So, a better way to do it is:


"if(vehicle == 'v' || vehicle == 'V') {


//do code for van


}else{


//do code for car


}"





In the actual if statement you're determining whether the vehicle variable holds a V or a v. Remember to enclose in single quotes('') because those are used for chars. You happen to know that if the vehicle is not a van, then it's a car. So you don't need another if statement asking if it's car, you know it is if it's not a van (so you use an else).





For the van code you need to check if the minutes are greater than 514 to assign a flat rate, or if less than 514 assign an hourly rate.





The first problem here is that instead of "if(hour %26gt;= 514)" you should write "if(totalTime %26gt;= 514)"





Then, instead of writing the opposite of that (if it's less than), you happen to know that if it's not greater than 514, it's less than. So use an else rather than a second if. And if it is less than 514, you need to calculate the number of hours the user has been there. Do this simply by writing: "cost = 3.5 * (exitHour - arrivalHour);"





For your car code, it's the same deal. Use the same adjustments you did for van in car.





Nearly done now.





Next, in your first S.o.p you need to say "vehicle" instead of "car".





In your second S.o.p you can simply say ("Exit time: " + exitHour + ":" + exitMinute);





You can then eliminate your third S.o.p.





And that's all! I'll write up the revised code for you and post it. And if you have any other questions feel free to send me an email.








edit:





Here's the revised code:





import java.util.Scanner;





public class Assignment


{


public static void main(String [] args)


{


int arrivalHour, arrivalMinute, exitHour, exitMinute;


double cost = 0.0;


char vehicle;





Scanner keyboard=new Scanner(System.in);





System.out.println("What kind of car do you have?(C for car or V for van)");


vehicle = myScanner.nextChar();





System.out.println("Enter arrival hour 0-23 ");


arrivalHour = keyboard.nextInt();





System.out.println("Enter arrival minute 0-59 ");


arrivalMinute = keyboard.nextInt();





System.out.println("Enter exit hour ");


exitHour = keyboard.nextInt();





System.out.println("Enter exit minute ");


exitMinute = keyboard.nextInt();





System.out.println("**************");


System.out.println("XXXXX");


System.out.println("**************");








int totalTime = (exitHour * 60 + exitMinute) - (arrivalHour * 60 + arrivalMinute);





if(vehicle == 'v' || vehicle == 'V') {


if(totalTime %26gt;= 514) { // more than 8.57 hours


cost = 30.0;


}else{


cost = 3.5 * (exitHour - arrivalHour); // 3.50 per hour


}





}else{


if(totalTime %26gt;= 600.0 ) { // more than 10 hours


cost = 20.0;


}else{


cost = 2 * (exitHour - arrivalHour); // 2.00 per hour


}


}





System.out.println("Parking for a" + vehicle);


System.out.println("Exit time: " + exitHour + ":" + exitMinute);


System.out.println("You need to pay : " + cost);


}


}


Which of the following string declarations contains an error?

a. char String1 [3]="xyz"


b. char String2 [5]="abcd"


c. char String 3 [7]="hello"


d. char String4 [ ] = "world"

Which of the following string declarations contains an error?
C. Variable names must be consecutive names with no spaces.

free survey

Please help me in this password code ?

Hi


I am inputing same password as akku . why its showing "wrong". Please tell me the mistake and giuide me in this code#include%26lt;stdio.h%26gt;


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





main()


{


char c;


char ppp[20] = "akku"; // correct password


char password[20];


int cnt=0;





printf("password:");





while( (c=getch()) != 13 ) // 13 is the code for enter


{


password[cnt] = c;


printf("*");


cnt++;


}


password[cnt] = '\0';





if(password==ppp)


printf("correct");


else


printf("wrong");





getch();


}

Please help me in this password code ?
Change if(password==ppp) to if(!strcmp(password,ppp)) .


Characters (strings) in C/C++ can not be compared with == operator . You have to use strcmp function instead .





Don't forget to include string.h header file .
Reply:An elaboration on the last answer:


When you create ppp[20] and password[20], you request the compiler to create these two lines:


char *ppp, *password;


ppp=new char[20];


password=new char[20];


This causes the name of the array to actually be a pointer to its first element, meaning the expansion of the expression:


a[x]


is actually:


*(a+x)


which works because of pointer arithmetic.


When you do the equality, it can be guaranteed that ppp and password do NOT have the same address, which happens to be what you are comparing. The only work around is to compare size then loop for every character. Luckily, strcmp(const char *, const char *) %26lt;string.h%26gt; does this for you, and returns 0 for equal strings, -1 for "less than", and 1 for "greater than".


A few simple questions from a newbie. About certain code.?

Hello. I used to program in C# a little bit, but after reading some things I've decided to push forward on C++. I have some doubts though that I can't seem to find the answer anywhere.





#include "Hello World.h"





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


{


//std::cout%26lt;%26lt;"Hello, World!";


std::cout%26lt;%26lt;"Oh my lord. This is me toying with the programmming code C++";


char myLine[100];


std::cin.getline(myLine,100);


return 0;


}





1. Do I have to always include? [code]int main (int argc, char* argv[])[/code]





2. I want to print "Hello World!" and on a separate line "Oh my lord. This is me toying with the programming code C++"





3. What does std, cout, cin mean? Are they short for something else? I'd like to know that way I'll remember them easily.





Thanks for the help guys. :)

A few simple questions from a newbie. About certain code.?
1. Sort of, you need a main function, but it can look like: int main() only.





2. You want to print out an end of line which is the string std::endl, so std::cout %26lt;%26lt; std::endl; in between your lines should do it.





3. std is the standard namespace, cout means C output and C input for cin.
Reply:std just means to use the standard cout, not any other cout that might be lying around.





If you put this line after your includes





using namespace std;





then you can get rid of the std::





Then for doing a newline you should use endl;





cout %26lt;%26lt; "Hello, World!" %26lt;%26lt; endl;





All programs need a main.





cout is the standard character output stream


cin is standard character input stream
Reply:I don't know what you read that made go from C# to C++ but I'll try to answer your questions:





Unless you are righting a very specific and simple program using the VOID MAIN(){....} //uses no return statement


And perhaps some simple functions added to that, then you do not need to include any header files.





I can guarantee though that there is no header file to include called "Hello World.h" unless you created one for some strange reason with code in it.





you do not require int main(int argc, char * argv[]) //unless you need your program to accept arguments at the command line (in DOS this would be something like "C:\%26gt;MyProgram.exe ARGS" or in UNIX, "Guest@UnixServer%26gt;./MyExecutable ARGS"





cout is a function, in which you need to include iostream: #include%26lt;iostream%26gt;, cout means console-out and will display what ever you need to, to the console (the screen).





cin also comes from the iostream header file and means take console input (keyboard) and store in a variable: cin %26gt;%26gt; myString;





I am not too familiar with std:: and I believe it has something to do with telling the code to reference the standard library (the header files). I don't think it is necessary if you include the correct header(s) depending on what you need (iostream, string, math, vector, etc). The only time you would need it is if you created something else that used cout or cin which would not be too smart.





I would highly suggest you stick with C#. C++ is great and it is where I did most of my development in college and a little before, but C# is perfect for Windows programming or building Web applications.





Depending on the compiler of C++ you are using, syntax may vary.





Unless you have a specific need to stay with C++, you should do C#. They are similar in syntax but it is easier in C# to create console apps, standalone apps, and web apps. You can even get express editions for free of C#, VB, and VisualC++ from microsoft.
Reply:You dont have to include the file if the file is incorparted. I dont know whats inside the hello world.h headers though.





Mind you The onyl knowledge I have for C++ is the general knowledge since I am a vb.net guy.





I think the cout means Line Out. Pretty much like "print on the screen".





Then the char myLine[100]; declares a varible. I dont know what the hundred means, but I have a 99% hunch that its a buffer in bytes.





the cin means "get from the screen" and the two parameters you used mean that the input from the from the cin should be stored in the variable.





the std probably just means that its getting the functions from the string class.





then you just return zero as your not returning anything in the function.





I hope that helps. I dont know anything about C++. I would never do C++ unless I am a professional at it. Its just .. its such a STRONG and LOW LEVEL language that even a simple print, and get statements require tedious code.





heheh


Read chars untill press enter. if press enter show d ans hw manytimes vowels r occured.code must be 1line in c

I will try:


int d;


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


if (strcmp(charR, "r") == 0)


{ d++; }


printf ("R appears %s ",d," times\n");


What do you think about Law Enforcement in Onslow N.C?

Urgency of Search for Marine Questioned


By MIKE BAKER – 3 hours ago





JACKSONVILLE, N.C. — For months after a pregnant 20-year-old Marine accused a colleague of rape, her family says, she continued to work alongside her attacker and endured harassment at Camp Lejeune. In the weeks after she disappeared, they believe, the sheriff's department was slow to act.





As authorities recovered Maria Lauterbach's remains Saturday from a fire pit where they suspect Marine Cpl. Cesar Armando Laurean burned and buried her body, her family asked why authorities didn't treat her case with greater urgency.





Naval investigators on Saturday said the pair had been separated on the job, a rape case was progressing and Laurean was under a protective order to stay away from Lauterbach. And Onslow County Sheriff Ed Brown insisted his department acted as best they could on the facts available.





"As soon as it went suspicious, we contacted the media and asked for help," Brown said. "The case did not produce enough evidence, other than she was just missing."





On Saturday, her burnt remains, and those of her unborn child, were excavated from Laurean's backyard.





"As well as I could see, the body was much charred," Brown said. "The fetus was in the abdominal area of that adult. ... That is tragic, and it's disgusting."





Authorities have issued an arrest warrant on murder charges for Laurean, 21, of the Las Vegas area. They say he fled Jacksonville after leaving behind a note in which he admitted burying her body.





In his note, Laurean wrote Lauterbach cut her own throat in a suicide, but Brown doesn't believe it and challenged Laurean to come forward and defend his claims of innocence.





Authorities have described a violent confrontation inside Laurean's home that left blood spatters on the ceiling and a massive amount of blood on the wall.





County prosecutor Dewey Hudson said Laurean had been in contact with three attorneys, including Mark E. Raynor, who declined to comment Saturday.





Lauterbach disappeared sometime after Dec. 14, not long after she met with military prosecutors to talk about her April allegation that Laurean raped her.





Her uncle, Pete Steiner, said that Lauterbach — stung by the harassment that eventually forced her to move off base — decided to drop the case the week before she disappeared.





Paul Chiccarelli, the special agent in charge of Naval Criminal Investigative Service at Camp Lejeune, told The Associated Press on Saturday that Marine commanders submitted requests in October to send the case to the military's version of a grand jury. A military protective order had been automatically issued in May and renewed three times.





"Anytime there is a sexual assault allegation involved, that's a standard routine," he said.





Lauterbach and Laurean served in the same unit of the II Marine Expeditionary Force, and court documents indicate Lauterbach's mother told authorities Laurean had threatened her daughter's career.





Steiner said Saturday on ABC's Good Morning America the Marines didn't separate the two personnel clerks, but Chiccarelli said Marine commanders assigned them to separate buildings on May 12.





Neither Brown or Hudson would say Saturday if they would have treated the case differently had they known about the protective order, which they discovered Friday night.





Chiccarelli said sheriff's office investigators were told about the order on Monday.





But Chiccarelli again said investigators didn't consider Laurean a threat to Lauterbach, or later a flight risk, because they had indications the pair were on friendly terms. He declined to detail those indications on Saturday.





Lauterbach's mother reported her daughter missing Dec. 19 — five days after she last spoke with her. By that time, she had been placed on "unauthorized absence" status by the Marine Corps.





"Several steps were taken to contact her via telephone, cell phone, even in person by sending Marines to her residence," said II MEF spokesman Lt. Col. Curtis Hill. "At that time, there was no reason to believe anything other than she had voluntarily placed herself in an unauthorized absence status."





Hill said that Lauterbach also left her roommate a note saying she was "going away" and apologized for "the inconvenience."





An Onslow County Sheriff's employee contacted Naval investigators Dec. 19 after hearing from police in Ohio and listed her as a "missing person at risk" in a national law enforcement database. He met with Lauterbach's roommate the next day, but court documents indicate he was unable to reach the Marine officer who had been notified of her absence, as he was away on holiday leave.





The employee checked ditches along several highways for her car, and asked the State Highway Patrol and several area hospitals if they had had any contact with the missing Marine. None had. He left word with the department radio room to contact him with any developments before leaving Dec. 22 for a vacation.





Steiner said he and his sister, Maria's mother, told authorities they planned to fly to North Carolina around the Christmas holiday, but were advised not to because authorities believed Lauterbach was headed for Dayton.





Believing that authorities "dropped the ball," Steiner said the Lauterbachs eventually decided they could no longer wait. They flew to North Carolina and met with detectives Monday, the same day court documents indicate authorities first discovered Lauterbach's ATM card had been used by a white male on Christmas Eve and she missed a prenatal care appointment on Dec. 26.





Brown also learned about the case Monday. A series of search warrants were filed, and the case went public and he asked for help.





By that point, it was too late. Laurean refused to meet with investigators, and eventually skipped town before dawn Friday without telling his lawyers where he was going.





Associated Press writers Estes Thompson in Raleigh and Jim Hannah in Vandalia, Ohio, contributed to this report

What do you think about Law Enforcement in Onslow N.C?
I could tell you , I used to live there!Right off Navy Blvd ,down from the front gate.


It's a small country town,that is a town because of the base.


Maybe that's one reason their slow,just my opinion.


The base wants to protect their image and try to keep this under wrap -not leak bad press of the Corps to the press. It just make all the Marines look bad.


It is disgusting and the man will get what's coming to him.

survey results

Anyone have these chars for mugen does anyone have sol,ogre,and mvc megaman my email is gorillazgalvan@yahoo.c

mugen chars

Anyone have these chars for mugen does anyone have sol,ogre,and mvc megaman my email is gorillazgalvan@yahoo.c
I'm sorry I don't really understand the question





I think you're talking about sprites .maybe not.





if you are click on this link I hope you find what you're looking for sorry I couldn't be of more help.





http://rcz.saphiria.net/img/sprites/shee...





or are you talking about emulators?


Is it bad to pass ints, chars, etc through a function that dosen't require them in C++?

for example....





void rabbit ( legs, eyes, ears, fur, ToyotaSupra)





note ToyotaSupra is not needed by rabbit but is still passed through it. Is that bad?

Is it bad to pass ints, chars, etc through a function that dosen't require them in C++?
Yes it is bad. If you don't need to use it why are you passing it? It is not clean code and doesn't make sense if another person is going to go through your code.


Need help starting my C++ code?

hello guys can someone make me a code, or just a start up for my code, her are the directions and some intro about my project code in C++. im tottally dont know how to make the two-dimensional array. if someone will guide me i appreacite it. HERE IT IS...


Thanks to the cool cell phones available today, most of us have typed a text message on our cell phones.


As you know, the numeric buttons on a phone also have letters associated with them. For example the number 3 has the letters DEF, the number 8 has TUV.


The method for entering the text is usually to press the numeric button a number of time to select the letter you want in the message. For example, since the number 5 has J-K-L on it, I would press 5 two times to select the second letter, 'K', if I wanted the letter 'C' I would press'2' three times to select the third letter.


Write a program to translate from a numeric entry to a text entry AND translate a text entry to a numeric one.


If the user enters:


3,1


2,1


8,3


4,3


3,1


/our program should print out "DAVID"


If the user enters "WAITT"


The program should print out 9,1 2,1 4,3 8,1 8,1


The maximum size of the TEXT message should be


around 50 chars


The TEXT should entered and printed out ON ONE LINE


The NUMERIC entry can be either as above or on one


line


Use 0 (zero) for space


Don't worry about using both small and capitol letters,


use only capitols OR small letters.


Do not even think about trying to write this without using


functions.


The NUMERIC output can be whatever you want, one


line or multiple lines, comma separated or dash or


whatever.


HINTS:


In the beginning, have the user select if they want to do 'NUMERIC TO TEXT" or TEXT TO NUMERIC" conversion, and then simply call the appropriate function(s)


Declare and initialize a 2 dimensional array with the phone keypad information.


For NUMERIC TO TEXT, use the user entry as the index into the array.


For TEXT TO NUMERIC conversion, scan the array with nested For loops until you find the correct letter, when you do, note what the array indexes are.


You may decide to NOT use the column array index ZERO, in which case leave the zero col filled with spaces or something. But if you choose to use indexes 1,2,3,%26amp; 4, remember you still have to take zero into account. The array index cannot start at 1

Need help starting my C++ code?
You say while (menuChoice != 3) but it has not been set to anything. You could say while(true) or while(1) and just return in your if(menuChoice == 3) block.





You need to parse the input into individual characters for the text convert and individual numbers for the num convert. You can do this by just using a char pointer, inspecting the character





At least in C++, you could declare your 2D array as char foobar[10][4] (assuming 10 numbers, 4 letters max on each).


Currently have the following for my code, but im not sure how to sort. (4) please help write in C language?

write the following in C language:





1. dynamically create an array of 1000 doubles


2. read unspecified number of doubles from a binary file


3. reallocate the array to amount of items actually read


4. sort all values in descending order (high to low)





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





int main(int argc, char** argv)


{


FILE *fp;


double *ptr, *reptr;


int length;


ptr = (double *) malloc(1000* sizeof(double));


fp =fopen("yourfilepathandname","rb");





length = fread(ptrr, sizeof(double), 1000, fp);


close(fp);


(double *) realloc(ptr, length * sizeof(double);











sort(ptr);


return 0;


}

Currently have the following for my code, but im not sure how to sort. (4) please help write in C language?
hey geekguy, bad news dude you have a corrupt system pal because everything in your system is on C:\ driver so if you know how to debug and format your hard drive it will fix these problems. you might try hitting start,programs,accessaries and system tools and restore to before it became corrupted but chances are it won't help pc repair can help just tell him that your C:\ driver is become corrupt and you want him to do a debug and format your hard drive and he will think that you know a lot about pc repair lol sorry man. But what your files is doing is repeating themselves or buy a new hard drive but they are expensive so do as the geeks all do is give good advice tell him what your pc is doing and it need a debug and format good luck and keep computing.
Reply:So you want to sort an array. There are lots of algorithms to do that. They are different in speed, memory usage and ... . Some famous ones are: Bubble sort, QuickSort, ...


The most simple one is bubble sort. You get an array and start with the first number. You compare it with the next one and if it is smaller, you change their places and so on. Then the second item and so on to the last item in array.


The pseudo-code will be like this:





procedure bubbleSort( A : list of sortable items ) defined as:


do


swapped := false


for each i in 0 to length( A ) - 1 do:


if A[ i ] %26gt; A[ i + 1 ] then


swap( A[ i ], A[ i + 1 ] )


swapped := true


end if


end for


while swapped


end procedure





You can find the other algorithms with a little search!





good luck.

community survey

This prog is suppsed to read an input file containing records: vehicle code weight(codes are m,c and b)Help!!

#include%26lt;iostream%26gt;


#include%26lt;iomanip%26gt;


#include%26lt;fstream%26gt;


#include%26lt;cstring%26gt;


using namespace std;





void GetRates(float%26amp;, float%26amp;, float%26amp;, float%26amp;);





enum Vehicles{MOTORCYCLE, CAR, BUS, TRUCK};











int main()





{


float cycleRate;


float carRate;


float busRate;


float truckRate;


char code;


int weight;


ifstream inFile;


bool invalidData;





inFile.open("vehicleCode.dat");


if(!inFile)


{


cout%26lt;%26lt;"Unable to open input file, program abnormally ended"%26lt;%26lt;endl;


return 1;


}





inFile%26gt;%26gt;code%26gt;%26gt;weight;


{


if(code=='m')


code=MOTORCYCLE;


else if(code=='c')


code=CAR;


else if(code=='b')


code=BUS;


else if(code=='t')


code=TRUCK;


else


cout%26lt;%26lt;"Error: Invalid Vehicle type";





}


if(100%26lt;=weight%26amp;%26amp;weight%26lt;=99000)


invalidData=false;


else


cout%26lt;%26lt;"Error:Invalid weight(non integer)";


Vehicles code;





switch(code)


{


case MOTORCYCLE:cout%26lt;%26lt;"MOTORCYCLE";


break;


case CAR:cout%26lt;%26lt;"CAR";


break;


case BUS:cout%26lt;%26lt;"BUS";


break;


case TRUCK:cout%26lt;%26lt;"TRUCK";


default:cout%26lt;%26lt;"Invalid vehicle type";


}








GetRates(cycleRate, carRate, busRate, truckRate);





cout%26lt;%26lt;"ROAD TAX REPORT"%26lt;%26lt;endl;


cout%26lt;%26lt;"Vehicle Type:"%26lt;%26lt;" Weight:"%26lt;%26lt;" Rate:"%26lt;%26lt;" Tax Due:"%26lt;%26lt;endl;





if(code=='m')


cout%26lt;%26lt;code%26lt;%26lt;weight%26lt;%26lt;cycleRate%26lt;%26lt;weight*...


else if(code=='c')


cout%26lt;%26lt;code%26lt;%26lt;weight%26lt;%26lt;carRate%26lt;%26lt;weight*ca...


else if(code=='b')


cout%26lt;%26lt;code%26lt;%26lt;weight%26lt;%26lt;busRate%26lt;%26lt;weight*bu...


else if (code=='t')


cout%26lt;%26lt;code%26lt;%26lt;weight%26lt;%26lt;truckRate%26lt;%26lt;weight*...











return 0;


}





void GetRates(/*out*/ float%26amp; motorcycleRate,


/*out*/ float%26amp; carsRate,


/*out*/ float%26amp; busesRate,


/*out*/ float%26amp; trucksRate)





{


bool invalidData;


invalidData=true;


while(invalidData)


{


cout%26lt;%26lt;"Enter the tax rate for MOTORCYCLES(0.01-0.99)"%26lt;%26lt;endl;


cin%26gt;%26gt;motorcycleRate;





{





if(0.009%26lt;=motorcycleRate%26amp;%26amp;motorcycleRate...


invalidData=false;





else





cout%26lt;%26lt;"Warning: entry invalid, rate must be between 0.01 and 0.99"%26lt;%26lt;endl;





}


}


invalidData=true;


while(invalidData)


{





cout%26lt;%26lt;"Enter the tax rate for CARS(0.01-0.99)"%26lt;%26lt;endl;


cin%26gt;%26gt;carsRate;


{


if(0.009%26lt;=carsRate%26amp;%26amp;carsRate%26lt;=0.999)


invalidData=false;





else





cout%26lt;%26lt;"Warning: entry invalid, rate must be between 0.01 and 0.99"%26lt;%26lt;endl;





}


}


invalidData=true;


while(invalidData)


{


cout%26lt;%26lt;"Enter the tax rate for BUSES(0.01-0.99)"%26lt;%26lt;endl;


cin%26gt;%26gt;busesRate;


{





if(0.009%26lt;=busesRate%26amp;%26amp;busesRate%26lt;=0.999)


invalidData=false;





else





cout%26lt;%26lt;"Warning: entry invalid, rate must be between 0.01 and 0.99"%26lt;%26lt;endl;





}


}


invalidData=true;


while(invalidData)


{





cout%26lt;%26lt;"Enter the tax rate for TRUCKS(0.01-0.99)"%26lt;%26lt;endl;


cin%26gt;%26gt;trucksRate;


{





if(0.009%26lt;=trucksRate%26amp;%26amp;trucksRate%26lt;=0.999)


invalidData=false;





else





cout%26lt;%26lt;"Warning: entry invalid, rate must be between 0.01 and 0.99"%26lt;%26lt;endl;





}








}





}

This prog is suppsed to read an input file containing records: vehicle code weight(codes are m,c and b)Help!!
Looks like the problem is your switch statement. Code is a char, but your switch is looking for cases using the full strings.





switch(code)


{


case MOTORCYCLE:cout%26lt;%26lt;"MOTORCYCLE";


break;


case CAR:cout%26lt;%26lt;"CAR";


break;


case BUS:cout%26lt;%26lt;"BUS";


break;


case TRUCK:cout%26lt;%26lt;"TRUCK";


default:cout%26lt;%26lt;"Invalid vehicle type";


}





should be like (mind the caps too, id convert em to be safe):





switch(code)


{


case M:cout%26lt;%26lt;"MOTORCYCLE";


break;


case C:cout%26lt;%26lt;"CAR";


break;


case B:cout%26lt;%26lt;"BUS";


break;


case T:cout%26lt;%26lt;"TRUCK";


default:cout%26lt;%26lt;"Invalid vehicle type";


}
Reply:What problems are you having, and make sure you aren't having capitalization problems on your data.


How do you change a character "1234" into it's numerical value in C?

In C, how do I change characters into Decimal values so I can use them to perform arithmetic operations with.


For example changing char '234' into decimal number 234

How do you change a character "1234" into it's numerical value in C?
use atoi





char[]="123";


int x=atoi(y);
Reply:The function you're looking for is called "atoi", and it's in the C standard library.
Reply:gets()





?








Not sure though...


Why does error "Illegal use of floating point value in function main()" in C++ code?

I'm doing a decimal to binary, octal and hexadecimal converter using C++. Actually, the code is still unfinished and I haven't started with the octal and hexadecimal part. Here's the code:





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


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





int main ()


{


double input, i, j, k, bin, oct, hex, counter, power;


char ans = 'y';





do


{


bin = 0;


oct = 0;


hex = 0;


counter = 1;


i = 1;


j = 1;


power = 1;


k = 0;





system ("cls");





cout %26lt;%26lt; "Enter an integer number [1-50]: ";


cin %26gt;%26gt; input;





while (counter %26lt; input)


{





while (i %26gt; 0)


{


j = i % 2;


k = k + pow(j,power);


power = power + 1;


}





cout %26lt;%26lt; bin;


}





} while (ans == 'y' || ans == 'Y');





return 0;


}

Why does error "Illegal use of floating point value in function main()" in C++ code?
First, almost all of your variables should probably be int, not doubles (floats). Unless you're dealing with possible fractional values (currency, for example) or potentially very large numbers (astronomical distances), ints are preferable.





That being said, the j = i % 2 could be the line causing the error. Using a mod operator (%) on a floating point value is a dubious operation, if it's even legal.





Hope that helps.





Edit: Just checked with Visual C++ Help system: "The operands of the remainder operator (%) must be integral. " This was the Standard C++ definition.





Edit in response to Additional Details: How do you get out of the innermost while loop? Look carefully at it.
Reply:No, actually, don't listen to Jeff G. Istream's operator%26gt;%26gt; is overloaded to many cases.





And by the way, i is never modified in the while loop. Do you see any i= or i%26lt;something%26gt;= in your while loop?





EDIT: Your do...while loop is also infinite because ans is never modified. You may want a cin%26gt;%26gt;ans just before the while line (not the one in the middle, the one at the end).





EDIT: Uhhhhhhhhhhhh...


I think your whole conversion process may be flawed. If I may, let me try to replace that internal while:





//Oh,. and set power to the highest power you want printed out.





while(i%26gt;0%26amp;%26amp;power%26gt;=0){ //FAILSAFE-no infinite loops because power is always decreased.


while(i%26gt;pow(j, power)){ //Increases the digit every time.


bin+=pow(10, power); //Inc this digit


i-=pow(j,power); //Take this out of the sum


}


}





//We SHOULD get here with power==0, if power


//is -1, a logic error occured and the while was terminated on


//the second term.





cout%26lt;%26lt;bin%26lt;%26lt;(power==-1?"LOGIC ERROR\n":"\n");


A program on a General tree having more than 2 child node in Data structure in C programming?

a C program on a General tree having more than 2 child node in Data structure in C programming. it is not a binary tree, but it should be a general tree where root node have three child node and each child node have three sub child node. want a help program


Basically this is the tree.


user


:


:


user1.................................... user2................................... user3


: ............... : ........................................... :


Hari Oum .......Sandeep ... Jeganathan


24 .. 23 ... 24


Prod Develpment .. Voice Application .. Java Application


and i m not sure but as i think u can use


for storing data


char *array[] = {"user","user1","user2","user3","Harioum...

A program on a General tree having more than 2 child node in Data structure in C programming?
Please try searching the web using yahoo or google.

order flowers

Comparing words to see if one is alphabetically before another, in C?

Where each letter of each word is stored in a listADT?





(the header would be something like...)





boolean listBefore(listADT list1, listADT list2)





- returning TRUE if the word in list1 is alphabetically before that in list2, and returning FALSE if it is not (I have written and included a boolean library obviously).





where listADT is a linked list, with each node made up of a 'char' component for the letter, and a pointer to the next letter.





If that makes sense. I'm quite new to C.





Can anyone tell me how to do this?

Comparing words to see if one is alphabetically before another, in C?
No, honestly using a linked list makes no sense and vastly complicates things.





Make your ADT a character array (i.e. C-string). If you are allowed to do so, use strcmp or strncmp. If those are forbidden and the point of the exercise is to write the comparison code yourself then you have more work to do.





Loop through the strings comparing each char. Watch for the null terminators on the strings. If the chars aren't equal, subtract the string2 char from the string1 char and return it. Whether it is positive or negative tells you which string is greater.
Reply:.... Why are you using a Linked list???





that aside just begin at the head of the list and do (char1%26lt;char2 %26amp;%26amp; char1!=char2). If that passes word one is first in the alphabet. If it failed do a comparsion on the same 2 chars but use %26gt; instead. If that passes then word 2 is first in the alphabet.


How can I solve a problem which i am facing in C++ File handling? Please read further...?

Consider the following program,





void main ()


{





int productno;





char productname[12];





ofstream fout(product.txt);





for(int i=0; i%26lt;5; i++)


{


cout%26lt;%26lt;"Enter product no %26amp; name \n";


cin%26gt;%26gt;productno%26gt;%26gt;produtname;





fout%26lt;%26lt;productno; cout%26lt;%26lt;"\t"


fout%26lt;%26lt;productname; cout%26lt;%26lt;endl;


}





fout.close ();





}





using this program, we can write product no %26amp; name for 5 products in text file. After that, if i open that file in Windows, the condents of that file will be in unreadable format with some symbols. How can solve this problem. I am using Microsoft Visual C++. Please help me... Thanks in advance....

How can I solve a problem which i am facing in C++ File handling? Please read further...?
I'd be wary of the logic in the program above. It doesn't look helpful to me.





It sounds like you are either writing to a binary file, which I doubt, or you have string problems. Are you typing in product names that are longer than 11 characters? If so, that could easily explain your trouble. Make productname 100 characters long, and see if that solves the problem.
Reply:Sorry I don't have a C++ compiler installed at work (as I work in Java) but give this a try...sorry if there is an error...as I do not have a compiler...but it should be much better then what you were doing there were multiple problems that I saw...I had to break the cin up because yahoo! replaced some of it with "..."





#include %26lt;iostream%26gt;


#include %26lt;fstream%26gt;


#include %26lt;cstdlib%26gt;





using std::ofstream;


using std::namespace;


using std::ios;





void main ()


{


int productno;





char productname[12];





ofstream fout("product.txt", ios::out);





for(int i=0; i%26lt;5; i++)


{


cout%26lt;%26lt;"Enter product no %26amp; name \n";





cin%26gt;%26gt;productno


%26gt;%26gt;productname


fout %26lt;%26lt; productno %26lt;%26lt; '\t' %26lt;%26lt; productname %26lt;%26lt; '\n';


}





return 0;


// Unnecessary because the ofstream destructor closes file fout.close ();


}





Also...as the commenter listed a learyness of logic...I did not change your logic within my code. I just added some basics...I made no logic changes.


How to convert a program written in wordpad and compile in c?

I want to write a program in wordpad and the open the file in c editor and then compile .


u may feel it as stupidity


bur if u want to write a large and complicated program and only want to know the output of the program.


for example (a program on web)


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





main(t,_,a)


char *a;


{return!0%26lt;t?t%26lt;3?main(-79,-13,a+main(-8...


main(-86, 0, a+1 )+a)):1,t%26lt;_?main(t+1, _, a ):3,main ( -94, -27+t, a


)%26amp;%26amp;t == 2 ?_%26lt;13 ?main ( 2, _+1, "%s %d %d\n" ):9:16:t%26lt;0?t%26lt;-72?main(_,


t,"@n'+,#'/*{}w+/w#cdnr/+,{}r/*de}+,/*...


,/+#n+,/#;#q#n+,/+k#;*+,/'r :'d*'3,}{w+K w'K:'+}e#';dq#'l q#'+d'K#!/\


+k#;q#'r}eKK#}w'r}eKK{nl]'/#;#q#n'){)#... i;# ){n\


l]!/n{n#'; r{#w'r nc{nl]'/#{l,+'K {rw' iK{;[{nl]'/w#q#\


n'wk nw' iwk{KK{nl]!/w{%'l##w#' i; :{nl]'/*{q#'ld;r'}{nlwb!/*de}'c \


;;{nl'-{}rw]'/+,}##'*}#nc,',#nw]'/+kd'...


#'rdq#w! nr'/ ') }+}{rl#'{n' ')# }'+}##(!!/")


:t%26lt;-50?_==*a ?putchar(a[31]):main(-65,_,a+1):main((*a == '/')+t,_,a\


+1 ):0%26lt;t?main ( 2, 2 , "%s"):*a=='/'||main(0,main(-61,*a, "!ek;dc \


i@bK'(q)-[w]*%n+r3#l,{}:\nuwloca-O;m .vpbks,fxntdCeghiry"),a+1);}

How to convert a program written in wordpad and compile in c?
Why don't you want to write the program using the C editor ?


Most src files are text based anyway so you can write a program in any text editor as long as you save it as plain ascii with the .c extension you can open it in a c compiler.





To avoid having to create a project look at the command line features of your compiler or get gcc for windows.
Reply:Step 1: Stop writing your programs in Wordpad. Either get a plain text editor. http://en.wikipedia.org/wiki/List_of_tex... Notepad++ works quite nicely on windows. Cream (Vim really) is amazing, if you can use it. And there's more respectable choices like PSPad, UltraEdit, ScITE, and so on.





Or better yet, get a proper IDE. http://msdn2.microsoft.com/en-us/vstudio...


http://www.codeblocks.org/


http://wxdsgn.sourceforge.net/





Step 2: Get a compiler. Visual Studio has Visual C++. You can get Visual C++ express for free, but you don't get Visual Studio for an IDE (use Code blocks or Dev-C++). Or gcc / MinGW (http://www.mingw.org/ ). If you write in a plaintext editor, you're going to have manually call the compiler and linker, etc. with the right arguments. If you have an IDE, that will be done automatically if you configure the IDE to use the compiler.


How do i pass an array of classes to a function in c++?????

i have a class declared:


class Restaurant


{ char restname[30];


/*Too many other variables and functions to list with yahoo's character limit of 1000 words*/ }





in my main function, i declared the class as an array:


Restaurant restdata[50];





now, HOW do i pass this array into a function, such as:


void InputFromFile( ??????);


which will read data from a file,


and then in each array element (which holds a copy of the class), store data in the variables and run certain 'set' functions





Any help will be GREATLY appreciated since this is a project for my final and my professor ran out of time and only gave us a 2 day crash course on c++


[By the way, I know C and know how to do this with structures, but im stumped now since c++ refuses to work when I try that process, but with this class instead]

How do i pass an array of classes to a function in c++?????
Example :


First of all, anytime you pass an array to any function, the syntax is as follows:





typeOfElementsInArray arrayName[ ]





So, let's apply this to your function:





void buildAccounts(Account* a[ ])


{


}





That's it. Don't make it harder than it really is. Another thing, remove the semicolon after the header of your function and the comment you have there "// function call" is incorrect because this is not a function call it's a function definition.





Now, where is "type" stored and how are you retrieving it? The thing is, you have not created your objects yet!! What you can do is something like the following (assuming the array contains a single person's accounts):





a[0] = new Checking;


a[1] = new Saving;


a[2] = new Credit;





We actually need to understand this better. Is this array of accounts just for a particular customer or it contains everyone's accounts? Please, try to clarify what you are doing with the array and the nature of your program so I can help you better.
Reply:void InputFromFile(Restaurant[50]%26amp; restdata)


{...}





That's passing the array by reference...there are a few other ways to do it but that's probably the best given the exact situation.

spring flowers

How do you make a character in C++?

OK i'm making this cardgame on a C++ program... and I have to "input the cards as they are dealt as characters", as it says in the instructions. So how do I make characters? Is it with char()? I tried that and it didn't work. Any suggestions?

How do you make a character in C++?
With a keyboard, make sure to use pixy dust before you start creating the characters otherwise theyll turn into mutants and rebel against you.


How can I make letters instead of numbers appear in base16 number in c++?

I'm doing a decimal to hexadecimal c++ program. However, instead of displaying A (or B or C or D or E or F), it displays 10 (or 11 or 12 or 13 or 14 or 15) instead. Here's the source code:





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


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


using namespace std;





int main ()


{


int input, i, j, k, result, power, hex_dig;


char hex_letter;





i = 1;


j = 0;


power = 0;





system ("cls");





cout %26lt;%26lt; "Enter an integer number [1-50]: ";


cin %26gt;%26gt; input;


k = i;


result = 0;


power = 0;


while (k %26gt; 0)


{


j = k % 16;


k = k / 16;





if (k %26lt; 10)


{


result = result + (pow(10,power) * j);


power = power + 1;


}


else if (k == 10)


{


hex_letter = 'A';


cout %26lt;%26lt; hex_letter %26lt;%26lt; j %26lt;%26lt; endl;


}


else if (k == 11)


{


hex_letter = 'B';


cout %26lt;%26lt; hex_letter %26lt;%26lt; j %26lt;%26lt; endl;


}


else if (k == 12)


{


hex_letter = 'C';


cout %26lt;%26lt; hex_letter %26lt;%26lt; j %26lt;%26lt; endl;


}


else if (k == 13)


{


hex_letter = 'D';

How can I make letters instead of numbers appear in base16 number in c++?
Store the k % 16 values of each iteration in a string of characters.


If (k %16) %26gt; 9, then 10 ≡ A ; 11 ≡ B ; 12 ≡ C ; 13 ≡ D ; E ≡ 14; F ≡ 15.


In the next step reverse that string using the function ' strrev() '.


That is your equivalent hexadecimal number
Reply:use C# -_-
Reply:I see that you read an integer into input, but I don't see where you do anything with that integer.





Why do you reinitialize hex_letter in each if else statement? Why not simply output the intended letter.





Or you could add 85 to each number, then 10 would equal 95, and 11 would equal 96, then cout the number without quotes and a letter will display. This would also eliminate all your if else statements.





95 in ASCII is capital A, 96 is B, etc.





You should also end your if else with an else, in the event none of the previous if else statements are entered.


Having problems executing a program with Dev C++?

ok, i'm a beginner. i typed up a source code from a book and put into into my compiler, Dev C++. There aren't any errors, but it just doesn't execute for some reason... take a look:


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


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





int main()


{


char weight[4];


int w;





printf("Enter your weight:");


gets(weight);


w=atoi(weight);





printf("Here is what you weigh now: %d\n",w);


w=w+1;


printf("Here is what you weigh after the potatoes: %d\n",w);


w=w+1;


printf("Here is what you are after turkey: %d\n",w);


w=w+8;


printf("And your weight after dessert: %d pounds!\n",w);


printf("Lardo!\n");


return(0);


}

Having problems executing a program with Dev C++?
The problem may be with some of the compiler settings. If you are running Windows Vista, the default settings for Dev-C++ won't work. Check out the users forum at http://sourceforge.net/forum/forum.php?f...


How to I write a C program???

How to write a C program that will print 1 when compiled and run on a little-endian machine and will print 0 when complied and run on a big-endian machine. The program should run on any machine regardless of its word size. (You can assume that a variable declared as unsigned char occupies one byte.)

How to I write a C program???
Well, that is the absolute beauty of C, isn't it. You can write a program that will give different results on different machines. Very useful for banking and space shots.
Reply:If an unsigned char is only one byte long, the endianness should not be a factor. This assumes UTF-8 character sets as well...

trading cards

Basic file I/O in C?

I have a past exam question like that:





Consider the following C code assuming that filename is a plain text file containing the following string:





0123456789





and none of the function calls fail, buffers are big enough, etc...








int fd1, fd2, fd3;


char buf1 = 'x', buf2 = 'x', buf3 = 'x';





fd1 = open("filename", O_RDONLY);


fd2 = dup(fd1);


fd3 = open("filename", O_RDONLY);


lseek(fd1, 4L, SEEK_SET);


lseek(fd2, 2L, SEEK_SET);


lseek(fd3, 7L, SEEK_SET);


read(fd1, %26amp;buf1, 1);


read(fd2, %26amp;buf2, 1);


read(fd3, %26amp;buf3, 1);








So,what will be the content of buf1,buf2,buf3. And explain why.





Can someone help me,please.

Basic file I/O in C?
But it wont compile correctly, filename is undefined, and the open functions (plus parameters such as _O_RDONLY) are OS\compiler specific. Thefore buf1, buf2, and buf3 all equal null.


I would like help with a C+ programmed desinged to work like a fast food menu??

F'Zone offers three different types of burgers to hungry students in Fairmont. You have to write a small program in C++ to calculate the price of a burger order. Your program should display the following menu to the user and prompts for his/her choice:











1: Quarter pounder combo





2: Bacon burger





3: Swiss mushroom burger








· If the user enters 1, then the program should ask the user if he wants the “biggy” size and if he wants to add cheese. The combo costs $4.59; “biggy” size costs $.39 more, and cheese costs $.25 more.





· If the user enters 2, then the program should ask the user if he wants to add cheese and fries. The burger costs $3.49; fries costs $.59 more, and cheese costs $.25 more.





· If the user enters 3, then the program should ask the user if he wants to add onion rings and a coke. The burger costs $4.99; onions rings costs $.79 more, and coke costs $.75 more.





· If the user enters anything else, the program should display an error message and terminate.











For the YES/NO answers, the user should enter an upper case 'Y' or 'N'. All prices include tax. Finally, the total of the order should be calculated and displayed in dollars and cents. The input/output of the program should strictly follow the format shown in the sample executions.








For character input, you should use the getchar function. Following is an example of how you can use this:





char x;


x = getchar();

I would like help with a C+ programmed desinged to work like a fast food menu??
#include %26lt;iostream%26gt;


#include %26lt;iomanip%26gt;





using namespace std;





int main() {





  cout %26lt;%26lt; "Welcome to F\'Zone\n"


      %26lt;%26lt; "\n"


      %26lt;%26lt; "Please select from the following menu.\n"


      %26lt;%26lt; "\n"


      %26lt;%26lt; "1: Quarter pounder combo\n"


      %26lt;%26lt; "\n"


      %26lt;%26lt; "2: Bacon burger\n"


      %26lt;%26lt; "\n"


      %26lt;%26lt; "3: Swiss mushroom burger\n"


      %26lt;%26lt; "\n"


      %26lt;%26lt; "To place your order, enter the number of the meal you would like.\n"


      %26lt;%26lt; "For instance enter 2 for a Bacon Burger.\n"


      %26lt;%26lt; "\n"


      %26lt;%26lt; "Please enter your selection now: ";


  char x;


  x = getchar();


  double total = 0.0;


  switch (x) {


    case '1' :


      total = 4.59;


      cout %26lt;%26lt; "Would you like a \'biggy\' size? It costs $0.39 extra.\n"


          %26lt;%26lt; "Type in a 'Y' or a 'N': ";


      //x = getchar();


      cin %26gt;%26gt; x;


      if (x == 'Y') {


        total += 0.39;


        cout %26lt;%26lt; "You have chosen to have a \'biggy\' size.\n";


      }


      cout %26lt;%26lt; "Would you like cheese with that? It costs $0.25 extra.\n"


          %26lt;%26lt; "Type in a 'Y' or a 'N': ";


      //x = getchar();


      cin %26gt;%26gt; x;


      if (x == 'Y') {


        total += 0.25;


        cout %26lt;%26lt; "You have chosen to have cheese.\n";


      }


      break;


    case '2' :


      // similar to 1, just change the price and messages.


      break;


    case '3' :


      // similar to 1, just change the price and messages.


      break;


    default :


      cout %26lt;%26lt; "You have not ordered a menu item.";


      return 1;


  }


  cout %26lt;%26lt; "The total of your order is $" %26lt;%26lt; setiosflags(ios::fixed)


      %26lt;%26lt; setprecision(2) %26lt;%26lt; total %26lt;%26lt; resetiosflags(ios::fixed);


}
Reply:So basically you don't want help, that is to learn. You just want someone to do your assignment for you, so you learn nothing. Here is your program.





#include %26lt;iostream%26gt;


#include %26lt;string%26gt;





using namespace std;





int main()


{


string question;





question = "no sense";





if (question == "sense")


{


cout %26lt;%26lt; "You rox my lvl 27 sox!";


}


else


{


cout %26lt;%26lt; "You seriously suck at asking questions" %26lt;%26lt; endl;


cout %26lt;%26lt; "Try doing your own work, or at least thinking about it before you ask" %26lt;%26lt; endl;


cout %26lt;%26lt; "WTF PWNED!!!" %26lt;%26lt; endl;


}


return 0;


}
Reply:Which class is this from? I would be interested in taking it.





Please do your own homework. It will really pay off in the end.


What is wrong with my c++ code?

I can't for the life of me figure out what is wrong with this.





for(int y=0; y%26lt;FileLength; y++)


{


for(int z=0; z%26lt;254; z++); //(b)


{


if(FileData[y] == KeyCodes[z]) //(a)


cout %26lt;%26lt; (char)z;


};


};





I get this error when compiling:


(a) name lookup of `z' changed for new ISO `for' scoping


(b) using obsolete binding at `z'





a and b indicate the lines that the errors point to in my compiler. I am using the Dev-C++ 4.9.9.2 beta.


Any help is appreciated thanks.

What is wrong with my c++ code?
i'm a rookie, but are you sure there is supposed to be a ; (semicolen) ending line (b) ?





isn't line (a) supposed to end in { for the statement on the next line?





for(int y=0; y%26lt;FileLength; y++)


{


for(int z=0; z%26lt;254; z++) //(b)


{


if(FileData[y] == KeyCodes[z]) { //(a)


cout %26lt;%26lt; (char)z; };


};


};
Reply:I suspect there's another definition of z earlier in the function. I'd change the variable in the loop.





Hope that helps.





Edit: The next answerer pointed out the problem: The stray semicolon provides the loop with an empty statement, therefore the now-detached if statement following it is using an obsolete variable.(z).
Reply:That dev c++ version is in beta I've had similar problems, you should just use a later version, and listen to cluck, his code seems to work.