Tuesday, July 14, 2009

C help needed?

Can anyone tell me how to execute DOS commands using C? I tried the following but it isn't working.


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


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


int main(void)


{


printf("Going to execute a C command");


system("dir");


return 0;


}


Iam just getting the printf statement executed. The dir command isn't working plz help!

C help needed?
I dont code much in windows, but what little I have seen, system command work just as well there.


I tried your code in Linux (with ls replaceing dir) and I got the expected result. So the program works for sure.


tell you what, check if adding a \n at the end of the print line changes things.


I have a feeling, you are running into buffer related issues.


The other thing that you can do is to change the command from dir to something like "mkdir a"
Reply:Try including Dos.h in your program. Write #include %26lt;dos.h%26gt;.





Have Phun Coding :)

garden flowers

How to allow unspecified number of parameters in C function?

For example, in C you have the function "printf" which takes a char* string with text, formatters, etc. and then you pass in a comma delimited list of variables for each parameter you provided in the first string. How do you define such a function? How do you make reference to these parameters? I assume there must be some base pointer which can be used to access the various entries?

How to allow unspecified number of parameters in C function?
Use "..."





I don't really get it, but there's some documentation here: http://courses.cs.vt.edu/~cs1704/notes/A...
Reply:Use ellipses in function definition:





void Foo( ... )





then use the following to get arguments:





va_list marker;


int first = va_arg( marker, int );


char* pSecond = va_arg( marker, char* );


...


va_end( marker );


Hey, please help me with some questions about C-Program!?

1) What are the header files in the C-Program?


2) What does "printf" do?


3) What does "scanf" do?


4) What are the data types in C-Languages?





This is for an assignment...





If possible, kindly include a site for my further info. Thanks a lot!

Hey, please help me with some questions about C-Program!?
1. header files are those files that hold the declarations of some of the functions and variables(and hence called "Pre-defined functions"). Those functions are put under different headers based on their function. Since those ".h" files are included usually at the top of a program file, they are referred to as "header files"





2. printf, a function under stdio.h(standard I/O header), prints a string- a raw string or values of variables - represented as format specifiers. it returns the total number of characters printed on to the standard console(Usually, the monitor)





3. scanf, a counterpart of printf, scans (or reads) values mentioned using format specifiers, from the stand console.(E.g. Key board). this too retrurns an integer, the total count of read characters.





4. Basic data types include:


int, char,float and double.


void can also be referred to as one of the data types.


Derived data types include:


Arrays, pointers and functions





"Let Us C" is widely acclaimed as the best guide for learning C.


Thank you,


Regards.
Reply:The headers file are files that contain prototype of many built in function in c program.





printf- is a function that allows u to display any kind of text in ur program.





the format is printf("your text");





as a result u'll get what ever u write in between the commas(in this case "your text") will be displayed in screen as u run the program.





But c program can't perform this function without a prototype(it tells c program how to perform). These prototypes are written in header files. So if u want to use printf function u will need to include the header files in ur program.





scanf- this function is used for take a input from ur keyboard and store it against a variable (u will have to define the variable name and data type first in ur program)





the format is scanf("%d", %26amp;name);





where name is the name of the variable and %d is a string that depends on the type of variable u are using.





data types are types of variables u can use on c program u will find details here





http://www.cplusplus.com/doc/tutorial/va...





try the whole website for more info
Reply:I think you can easily do what the rest of us do, like google your questions. You are getting us to do the work for you, but there is a positive to it, that if we do not know the subject we get to learn it along with you.





http://snap.nlc.dcccd.edu/learn/nlc/prin...





http://www.devx.com/tips/Tip/14539





http://www.unet.univie.ac.at/aix/libs/ba...





http://groups.google.com.au/groups?q=hea...





http://groups.google.com.au/groups/searc...





I wonder though if it isn't yahoo staff who prepare these questions to get us involved, for it is common sense what one needs to do....but whatever...

calling cards

The difference between stream output and printf is :?

a. type and formatting info is not used with stream I/O.


b. stream I/O can be directed to any output device


c. stream I/O is faster


d. printf cannot be used in C++

The difference between stream output and printf is :?
b


Studying for final, need help with c?

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


#define N 100





int main()


{


---int c, i = 0;


---char s[N];





---while((c = getchar()) != '\n' %26amp;%26amp; i %26lt; N)


------s[i++] = c;





---s[i] = '\0';


---printf("%s\n", s);





---return 0;


}





there are two bugs in this program, what are they?(hint: look for errors at the boundaries)





okay ive compiled this program and everything, i ant seem to figure out what the errors should be, i copied/pasted this directly from an old exam. Any help please

Studying for final, need help with c?
the while loop limits i to 99. however it will be incremented to 100 in s[i++]=c; s[N] is s[100], which i think in C means it can have element from s[0] to s[99]. So your array will be out of bounds when i=100.


also it seems like s[i]='\0'; overwrites the last entered character.
Reply:there is no bug in the program


the program prints what ever the input you give
Reply:while((c = getchar()) != '\n' %26amp;%26amp; i %26lt; N-2)


------s[i++] = c;


/*


i points to the last array element now, no "out-of-bound" errors.


*/


Solve this...any c++ programmers out there..?

a simple c++ program--%26gt;


main()


{ static int a[]={97,98,99,100,


101,102,103,104};


int*ptr=a+1;


print(++ptr,ptr--,ptr,


ptr++,++ptr);


}


print(int *a,int *b,int *c,int *d,int *e)


{


printf("\n%d %d %d %d %d",*a,*b,*c,*d,*e);


}





help me with its o/p....i m not getting it..


its showing 100 100 100 99 99


but i thought 99 99 98 98 99

Solve this...any c++ programmers out there..?
This is due to the fact that the compiler execute printf from right to left internally but prits the output Left to Right. So if you look at the printf this way you will understand the output. i.e





1st execution will be ++ptr


2nd execution will be ptr++ and so on......
Reply:The print( ) statement with all the incremented and decremented ptr arguments can give different results on different C compilers, because there is no rule for the compiler about the order in which the arguments should be evaluated.





b, c, d and e are not declared, so the program should not compile anyway, and they are not initialised, so if it somehow compiles, the results of their print( ) statements could be anything.


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);


}

pokemon cards

Can you help me debug this c++ program [update a file]?

#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;





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 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, 0);


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


fclose(bookfile);


}





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


{


int found=0, 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);


}





void searchNupdate(void)


{


char rep, target[6];


int size=0;


int found=0;





displayTitle();


do


{


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


gets(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(%26amp;size);


}


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);


}

Can you help me debug this c++ program [update a file]?
Can you give a hint on what function the error occurred?


Need help wit 'c' program?(its not executing the answer when im giving a uppercase alphabet)?

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


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


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


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


main(){


char n;


clrscr();


printf("enter any single character...");


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


if(isupper(n))


{


printf("given character is a uppercase alphabet\n");


exit(0);


}


printf("given character is not a uppercase alphabet");


getch();


}

Need help wit 'c' program?(its not executing the answer when im giving a uppercase alphabet)?
i use c++, you dont use else in c? if you do, then your code is wrong, (you might notice that your {} are wrong as well),it should be:





if(isupper(n))


{


printf("given character is a uppercase alphabet\n");


exit(0);


}


else


{


printf("given character is not a uppercase alphabet");


getch();


}








----EDIT----


apparently you do use else, so yeah, thats your problem.





http://www.cprogramming.com/tutorial/c/l...
Reply:#include%26lt;stdio.h%26gt;


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


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


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


main(){


char n;


clrscr();


printf("enter any single character...");


n=getchar();


if(isupper(n))


{


printf("given character is a uppercase alphabet\n");


exit(0);


}


printf("given character is not a uppercase alphabet");


getch();


}








Try this. it can help.
Reply:nn is right, you are likely getting BOTH messages, instead of getting just one.


NEED BADLY!!need tommorow please help me..turbo c problem?

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


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


main()


{


char W;


int A,H;


clrscr();


printf("What is the name of my school?");


printf("a.La Salle,b.UST,c.UE,d.UP");


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


if(W-'a')


{


printf("Correct!!!\n");


A=0


H=A+1


printf("Your Score is %i",H);


}


else


{


printf("Wrong\n");


}


getch();


return 0;


}





please help me...else function doesn't work ..please i need it tommorow ASAP..tnx!!


really apprecitate it

NEED BADLY!!need tommorow please help me..turbo c problem?
If the correct answer is "a", then your test needs to be


if (W == 'a')





Your current code will score b,c and d as correct, but not a.
Reply:u didn't mention what error u r getting? always mention error while asking for help.


i think the error is at line


if(W-'a')


it shd be


if(W=='a')


try it... and then compile....
Reply:remove clrscr() and try to compile n run this code





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


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


main()


{


char W;


int A,H;





printf("What is the name of my school?");


printf("a.La Salle,b.UST,c.UE,d.UP");


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


if(W-'a')


{


printf("Correct!!!\n");


A=0;


H=A+1;


printf("Your Score is %i",H);


}


else


{


printf("Wrong\n");


}


getch();


return 0;


}


How would I put this into C++?

printf("%s\n\n", line);


printf("Press enter");


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





The only one I can figure out is the second one


cout %26lt;%26lt; "not sure", line %26lt;%26lt; endl; // need some help with this one


cout %26lt;%26lt; "Press enter" %26lt;%26lt; endl;


cin %26lt;%26lt; "not sure", %26lt;%26lt;%26amp;play_again %26lt;%26lt;endl; // that could be right

How would I put this into C++?
cout%26lt;%26lt;line%26lt;%26lt;endl%26lt;%26lt;endl;





cout%26lt;%26lt;"Press Enter";





cin%26gt;%26gt;play_again;
Reply:cout %26lt;%26lt;"not sure "%26lt;%26lt;line%26lt;%26lt;endl;


cout%26lt;%26lt;"press enter";


cin%26gt;%26gt;play_again;
Reply:cout%26lt;%26lt;"%s", %26lt;%26lt;line%26lt;%26lt;endl;


cout%26lt;%26lt;"press enter"%26lt;%26lt;endl;


cin%26lt;%26lt;"%c, %26lt;%26lt;%26amp;play_again%26lt;%26lt;endl;

plum

Are Turbo-C++ and Dev-C++ same?

If it is the same, why simple commands like printf working on Turbo-C++ not working on Dev-C++ ?

Are Turbo-C++ and Dev-C++ same?
They are absolutely different. Turbo C++ is a product of Borland Software, developing their turbo C product with a front-end licensed from TauMetric (now part of Sun).





DevC++ is a Microsoft Windows implementation of the GCC (GNU Compiler Collection). It runs on top of the MinGW implementation of the GNU tool chain, which essentially means it uses a minimal Unix/Linux emulator.





I am very surprised you are having trouble with DevC++. I never did ( though I switched to Linux a few years ago) and this is the first time I've heard of anyone having a problem with it. It is actually a more complete implementation of the ANSI C++ standard than TCC is. They are not the same product at all.
Reply:no, turbo c++ is turbo c++, dev c++ is dev c++.
Reply:both compilers, but not the same. different command for a similar function.


C compiler help please?

I downloaded DevC++.. It compilers, make exe file but when it tries to run the DOS promt snaps one second and thats it no running


even simple codes like


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


int main(void)


{


char ch='a';


int i=97;


printf("value of ch: %c; value of i: %c \n", ch,i);


return 0;


}

C compiler help please?
use gethch(); before closing curly braces in your program to pause the till yuo press any key
Reply:Hi,





Include the following line before the "return 0;" statement,





getch();





This statement will make your program to wait for the user to press a key from the keyboard; and hence your DOS window will not close with a flash and will wait for you to press a key.
Reply:Try running the programs under the DOS prompt.


This is a console programs which open a DOS style output screen then close it when finished.


But if you are already running a DOS prompt, then the output of this program will go to this screen.


Why doesn't this C function work more than once?

CONTINUE (void) {


char cont=1;


printf("\n(Press c, then return to continue.)");


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


if (cont == 99) {


printf("\n...");


return 0;


}


else {


printf("\nInvalid input");


return 1;


}


}

Why doesn't this C function work more than once?
This is an annoying problem with Scanf. It cashes the value and hence why your not prompted. You need to clear the Scanf cache but I cant remember how to do that.





I think one way of clearing the cache automatically is to allow a space between arguments in a scanf function. For example :





printf("\n(Press c, then return to continue.)");


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





and not





printf("\n(Press c, then return to continue.)");


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








Notice the space between the " and % in the scanf function. Give that ago and see if it fixes the problem.
Reply:because scanf() extracts the first character from the input the first time, but leaves the end of line char there. The second time around the eol gets extracted from the input without any delay.


Use gets() or (better) fgets() instead - just read the whole line into the buffer, and then look at the first character.
Reply:Start your program with flushall() or flush(stdout)/ flush(stdin) ..It will clear the buffer that is occupied by scanf function..


Problems with my c++ program not executing the right way...could anyone tell me how im getting this problem?

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


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


#define MaxStringLength 500


int main( int argc, char** argv )





{





char userString[MaxStringLength] = "";


char charString;


int i = 0;


int numOccur = 0;





printf( " Enter any string: ");





while( i %26lt; MaxStringLength)


{


userString[i] = getchar();





if( userString[i] != '\n' )





i++;





else





break;


}


userString[i] = '\0';





printf( " Enter any character: ");





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





i = 0;





while( userString[i] != '\n' %26amp;%26amp; i %26lt; MaxStringLength )


{


i++;


if( userString[i] == charString )


numOccur ++;


}





printf( "In the following string: \"%s\"\n", userString );





printf( "The character \'%c\' appears %i times", charString ,numOccur );





return( 0 );


}








**/ That is my program. Whats happening is once i get the user input for what character theyd like, it doesnt keep running, you have to like type something in for it to continue runningthrough. Help!

Problems with my c++ program not executing the right way...could anyone tell me how im getting this problem?
#include %26lt;stdio.h%26gt;


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


#define MaxStringLength 500





using namespace std; // using namespace container.





int main( int argc, char** argv )





{





char userString[MaxStringLength] = "";


char charString;


int i = 0;


int numOccur = 0;





printf( " Enter any string: ");





while( i %26lt; MaxStringLength)


{


userString[i] = getchar();





if( userString[i] != '\n' )





i++;





else





break;


}


userString[i] = '\0';





printf( " Enter any character: ");





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





i = 0;





while( userString[i] != '\n' %26amp;%26amp; i %26lt; MaxStringLength )


{


i++;


if( userString[i] == charString )


numOccur ++;


}





printf( "In the following string: \"%s\"\n", userString );





printf( "The character \'%c\' appears %i times", charString ,numOccur );





system("pause"); // this function call pauses execution.





return( 0 );


}








done. you needed to use the system("pause"); call in your program.

parts of a flower

How to print the result in c language?

My actual question is how to print the result or some other thing using c language.


for example:


printf("\nName:X\nFrom:XX...........")...


output will be:


Name:x


From:XX..........





This output i should print in a paper.Pls help meeeee............

How to print the result in c language?
If you want to print variables and string using printf.. you will need to do:


printf("\nName:%s\nFrom:%s\n", str1, str2);





Output: (str1 = John, str2 = Yo)


Name: John


From: Yo


Easy Question: How do you output a C program to a text file?

So let's say there's a C file named test.c





gcc test.c creates an a.out





how do I make the compilation put test.c's output (the printf's) into a text file?





Thanks for the help!

Easy Question: How do you output a C program to a text file?
OK you need to understand the difference between what a printf() is doing within your code and what the output of a compiler is outputting to the screen.





1) The printf() calls only work when you are running the program you have already compiled and its an executable ie .exe.





If you want the printf output to be placed in a textfile then swap the printf()s for fprintf()s and set up the following.





/* file pointer for text file */


FILE *fp;





/* Open the file for writing */


fp = fopen("example.txt", "w");





print("This goes to the screen\n");


fprintf(fp, "This goes to the file\n");


fclose(fp);





After running the executable a file called example.txt should exist that has the line 'This goes to the file' in it.





2) if you want the output of the compiler then all you would do is pipe it to a file eg





gcc test.c %26gt;%26gt; example.txt





printf()s have nothing to do with the compilation or linking stage.


C++ little problem?

I'm having problem with this piece of code:





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





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











void main( )





{





int y=0, r=0, c=8;





do{





clrscr( );





printf(“value:”); scanf(“%d ”, %26amp;y);





if (y = = 0)





r = r+1;





}while(y%26lt;=100);





printf(“ r = %d”, r);





}





****


ok, now my question is:


does this determine:


a) counts the number of zeros entered in n numbers that are lower than 101


b) counts the number of zeros entered in n numbers that are lower than 100





really having trouble with this, already did many tests but can't get to a conclusion, any help would be greatly appreciated.

C++ little problem?
Look at this from your program:





while(y%26lt;=100);





What this means is that the code in the loop will execute when the condition is true. In this case, the condition is that y is less than or equal to 100. So, when y is 100 the loop will still execute. But that is it. It will not work past 100. That means that it will count the numbers until it gets to 100 -100 will be counted.





So a) is the correct answer.
Reply:Choice a is the answer.
Reply:Entering in 100 would not get counted but the loop continues.





Entering 101 would not get counted and the loop would stop.





I would say both answers are correct. But, to stop the loop A would be the answer.





bad question though...if they are trying to teach while loop condition stops. Bad bad....


What c++ and c file extension?

example for c++ --%26gt; test.cpp





are "printf" and "scanf" commands in C++ or C

What c++ and c file extension?
c++ file name extention is .cpp


c file name extention is .c





printf and scanf commands belong to language C
Reply:The file extension in C is .c like test.c and


in C++, the extension of file is .cpp, like test.cpp.





The printf and scanf are the standard output and input commands in C. But these can be valid in C++.


The same commands are cout and cin objects respectively in C++.
Reply:The are in C++ ..





Thats a guess...





ok.


.


bye...
Reply:for c : myfile.c


forc++ : myfile.cpp


for using "printf" and "scanf" commands in C : #include %26lt;stdio.h%26gt; befor main
Reply:I'm sorry iyiogrenci but printf and scanf are also in C++ language!they are predefined with %26lt;stdio.h%26gt;;


scanf allow you to insert data from file like "file%26gt;%26gt;x" for %26lt;fstream.h%26gt; and printf allow you to print data into file like "file%26lt;%26lt;x"


for %26lt;fstream.h%26gt;

mothers day flowers

Can somebody help me?please correct my errors (Turbo C)?

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


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


main()


{


int A,B,C,D,X;


clrscr();


printf("FIRST QUESTION 1+1=?);


printf("CHOICES A.2,B.3,C.4,D.5");


scanf("%i,%26amp;A);


if(A = ='A')


{


printf("Correct!!!")


}


else


{


printf("Wrong")


}





it doesn't work the way i want to..please help me..im just a 13 yr old..can anybody lend me a hand?thanks...

Can somebody help me?please correct my errors (Turbo C)?
#include%26lt;stdio.h%26gt;


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


main()


{


int ans;


clrscr();


printf("FIRST QUESTION 1+1=?);


printf("CHOICES A.2,B.3,C.4,D.5");


ans = getchar();


if (ans=='A' || ans=='a')


{


printf("Correct!!!")


}


else


{


printf("Wrong")


}


return 0;


}
Reply:You should either do a strcmp() or compare if(A==1) since you have A declared as an integer (and read in that way) but comparing it to a character. Unless you are looking to compare ASCII values... Also, you are missing an ending " in your FIRST QUESTION printf() statement.





And as matter of style, your main() function should return something or mark its return as void. And use useful variable names...
Reply:printf("FIRST QUESTION 1+1=?);


scanf ("%i,%26amp;A")


Dont give them a choice if you do, make it just


printf("CHOICES 2, 3, 4, 5");





A2 B3...its confusing huh?





int A=0;


int a=2;





/*int b=3;


int c=4;


int d=5; aren't being used yet*/





So you get a number.


Then


if( A==a)//compare their answer to your variable
Reply:put it on desktop reset windows


I have problem in programming! pls answer this..It is .c file extension?

how do I make a program that never goes down even if i press enter? it will remain only on the same line.


EXAMPLE of my program:


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


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


int main()


{


int major,minor,line,line1,units,sUnit;


float grades,wpa,msca,grade1,sum,average,avera...


char another='Y';


printf("Press Enter to Start...\2\n");


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


system ("cls");


printf("\nHow many major subjects you have: ");


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


printf("Supply equivalent grade and unit for the major subjects:\n\n");


printf(" GRADES UNITS\n");/* after I key in the grade it must not go down


even if I press ENTER, it must be in the same line*/


for(line=1; line%26lt;=major;line++)


{


printf("(%d) Major subjects:\t ",line);


scanf("%f",%26amp;grades);


printf("\t");


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


}


getch();


return 0;


}








\\try to paste this on your program.

I have problem in programming! pls answer this..It is .c file extension?
the line will move down because of "echo" on the terminal





best way is to output ANSI terminal escape codes to move the cursor back up to the previous line





for reference:





ESC = ASCII#(27)





printf("\033[1A") moves the cursor up a line on most termninals


Can we print a statement on out put screen without using any print statements in c-programing language?

if i want want to print "hello" or any other string generally we use printf statement in c-language.But i want to know ,can we print a string on out put console witout using printf statement

Can we print a statement on out put screen without using any print statements in c-programing language?
Printf() is what is typically used from the Standard C Library. However, if you need to make a non-standard call, there are usually operating system specific functions to accomplish native I/O. Printf() is portable but other calls won't be cross-platform.





If you're writing in terms of Unix, take a look at the Curses Library (see links below). Using curses, programmers are able to write text-based applications without writing directly for any specific terminal type. The curses library on the executing system sends the correct control characters based on the terminal type. It provides an abstraction of one or more windows that maps onto the terminal screen. Each window is represented by a character matrix. The programmer sets up each window to look as they want the display to look, and then tells the curses package to update the screen. The library determines a minimal set of changes needed to update the display and then executes these using the terminal's specific capabilities and control sequences.





For the DOS console, you'd most likely make BIOS calls (interrupt 10h) which printf() eventually ends up executing. If you have a Windows-based system, there is always DirectX or OpenGL...





For completeness, I should mention that on some machines, there is memory-mapped I/O for the video hardware. Therefore, you could determine the method to address the video hardware directly assuming the OS allows it (without writing your own device driver). You'd need to be much more specific with your question to determine if this is what you're seeking.





Note: tadds, you're supplying C++ code (Stream I/O) instead of the requested C-only advise.
Reply:Try this





#include %26lt;iostream%26gt;


using namespace std;





int main()


{


cout %26lt;%26lt; "hello";


}
Reply:The first guy is suggesting a different programming language and unfortunately has no idea what he's talking about and absolutely no right to be giving you information.





I'm not sure what you're asking in your question as it appears to ask two different things. First, you want to know if you can print to the screen without calling a print statement. This is, of course, not easily done as you would have to edit the process of the console to manipulate the text in the console. Attempting to access data outside of your program's scope will not be allowed by the operating system so some significant hack work would be involved.





Then you ask if you can print to the screen in C without printf()... sure, if you use another function. How about... fprintf()?





fprintf(stdout, "Hello");





You should be using fprintf() over printf() anyway. As the second poster said, there are other methods to write text to the screen.


Why does this piece C code work?

Why did the following program work?





Please note that i is an integer and s[] is an array.


How i[s] is interpreted?








main()


{


char s[ ]="worst";


int i;


for(i=0;s[ i ];i++)


printf("\n%c",i[s]);


}

Why does this piece C code work?
The trick to this program is to understand why i[s] is the same thing as s[i]. I will try to explain this.


Firstly, its important to understand what x[i] means.





In C, if x is an array, then it just contains a pointer to the first element in the array. We can rewrite x[i] using pointer arithmetic as:





*(x + i) [do you understand why?]





Just to be sure that this form is correct, lets check it for x[0]:





*(x+0) = *x





Now since x is a pointer to the first element in the array, this identity is true. Now let us have a look at your example





s[i] = *(s + i)


but what is i[s]?


i[s] = *(i + s)





Now simplifying that last equation, we know that (i + s) is the same is (s + i) which means that


*(i + s) = *(s + i)


which means that s[i] = s[i].





Hope that helped!
Reply:ya, its possible, i[s] is just another representation of s[i]. it'll print "worst" in the console.
Reply:s is a character array containing 6 characters---w,o,r,s,t and a '\0' (null character) in the end. ASCII value of '\0' is zero.





so if you write


printf("%d",s[5]);


it will print 0 because the ASCII value of '\0' is zero.








The for loop will run until ASCII value of s[i] is non-zero.


___________________


I suggest you join this forum:


http://cboard.cprogramming.com/

song downloads

Microsoft Visual C++ 2005 Express Edition debug problem?

when i do the debug in the program the cmd appears quickly then close.


to know the code is :


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


int main ()


{


printf ("welcom to c ");


return 0;


}

Microsoft Visual C++ 2005 Express Edition debug problem?
It appears quickly and closes because that's the end of your program. After your printf(), pause for a console input (like Console.ReadLine() or cin %26gt;%26gt;). That will force your user to hit enter to end the program.
Reply:Add the function 'getch()' at the end to cause it to wait for you to press a key.
Reply:Your program is working fine keep on adding to it..


why using Standard (Stdio) not (iostream)


C++ problem?

How do I tell the program that the last number entered was the same.


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





int


main()


{





int a, b, c, d, e, total;





printf ("Enter a number : "); /*recieve first number*/





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





if (a%2==0)


{


printf ("The entered number is EVEN.\n");





}


else


{


printf ("The entered number is ODD.\n");





}





printf ("Enter a number : "); /*second number*/





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





if (b%2==0)


{


printf ("The entered number is EVEN.\n");





}


else


{


printf ("The entered number is ODD.\n");





}


if ("%d=%d", b, a);


{


printf("That is the same number.\n");


}


This is only part of the program. If i enter 3 first than 4 it says I just entered the same number. I think by using 'if' I need to use 'else'.


I want it to tell the user that they entered the same number as the number previous when they actually do.

C++ problem?
you're incorrectly using the "=" The single "=" means you set a varible to the next.





Since you're using c++ you can use if (a==b). That will compare a and b.





a=b makes the varible a equal to b.





As good programming practice you should give your variables meaningful names. ie. Num1 and Num2 instead of a and b
Reply:In your another post I couldn't find a "answer to this question" button, anyway yes you must use: printf or cout to print out.





In c/c++ for equality comparision you must use "==".


In your code you had written:





if ("%d=%d", b, a);


{


printf("That is the same number.\n");


}





but the correct form is as follows:





if (b==a);


{


printf("a and b are equal.\n");


}
Reply:The problem is you have a semicolon after your if statement.


if ("%d=%d", b, a);


Also, your if statement doesn't make sense. You need to use:


if(a == b), which means if a equals b. a = b in C will assign a to b, and it will always be true unless b is equal to 0.


That will always terminate the if. You won't need an else statement.





Good luck!


What does this c code output? Really simple and Easy!?

Determine the order of execution of operations in the code below. Determine the sequence actively.





{ int A=9,B=3,C=1;


printf(“%d %d %d %d”, A++,--B,C++,A*B*C);


}








nothing I try working for me on this prob! =(

What does this c code output? Really simple and Easy!?
offhand, I believe its..





9 2 1 27





not sure if i'm right though





edit: I just ran it, I'm right, that is what it is. But if you're in a programing class, this is something you do need to figure out for yourself


What is wrong with my program? [help in c programming]?

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


int main(void)





{


float x,y, result;


char cop1;





printf("Choose among the following operators:\n+,-,*,/", cop1);


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





if (cop1=='/')


{


printf("Enter Dividend\n", x);


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


printf("Enter Divisor\n", y);


scanf("%f", %26amp;y);


printf("result=%f\n",x/y);


}


else if (cop1=='+')


{


printf("Enter 1st addend\n", x);


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


printf("Enter 2nd addend\n", y);


scanf("%f", %26amp;y);


printf("sum=%f\n",x+y);


}


{


else if (cop1=='-');


printf("enter minuend\n", x);


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


printf("enter subtrahend",y);


scanf("%f",%26amp;y);


printf("difference=%f", x-y);


}


{


else if (cop=='*');


printf("enter 1st factor\n", x);


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


printf("enter 2nd factor\n",y);


scanf("%f",%26amp;y);


printf("product is=%f\n",x*y);


}


else


printf("Wrong!\n");





return=0;


}





calculator.c: In function 'main':


calculator.c:28: error: parse error before 'else'


calculator.c:36: error: parse error before 'else'


calculator.c:43: error: parse error before 'else'

What is wrong with my program? [help in c programming]?
Here are the reasons why it won't currently compile (some of which you haven't found yet):





[[ 1 ]] You have opening braces in the wrong places:


{


else if (cop=='*');


They should be right after the else-if clause, not before.





[[ 2 ]] You have a semicolon after some else-ifs:


else if (cop=='*');


Take them out.





[[ 3 ]] The last else-if says "if (cop=='*')." It should be cop1, not cop.





[[ 4 ]] Finally, at the very end, you have "return=0;" Leave out the "=". It's just "return 0;"





Fix those errors and your program seems to work correctly. Nice job.
Reply:First of all, you have an opening brackets "{" right before else as well as inconsistent if{}else{} statements.


I'd suggest you to utilize indentation so you would see where your clauses begin and end.
Reply:Hi!





Seeing your various printf statements doesn't allow me to believe that you could make you a small mistake in the beginning. You could program very well.





Errors:


1. Your first printf statement. The quote doesn't include the variable name or instead remove if not needed.





2. Misplaced curly brackets. You have done well in your first two if..else blocks.





3. No semi-colon after if condition.





4. return 0;





Advise:


You can better improve your program if you would have used printf statements for once in the beginning i.e. before the if..else blocks instead of placing them in each block.





Sorry but you have to look for own small mistakes.


Enjoying programming at your level best. Try harder and harder, if unsuccessful then make a request. Goodluck!





Gagan..


C++ help ?

I am having problem using printf function in C++, i am new to C so what changes shud i make in the below program ?





/*Ramesh Basic Salary*/


main ()


{


float DA,HRA;


float GS;





DA = 0.2;


HRA = 0.4;





/*Ramesh's Gross salary is sum total of DA and HRA*/;





GS = 10000*.2+.4;





printf("%f" , GS);


}

C++ help ?
You need to include the stdio.h header in the source code in order to use the printf() function declared in it. At the start of your program add the following.





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





/*Ramesh Basic Salary*/


main ()


{


float DA,HRA;


float GS;





DA = 0.2;


HRA = 0.4;





/*Ramesh's Gross salary is sum total of DA and HRA*/;





GS = 10000*.2+.4;





printf("%f" , GS);


}
Reply:#include %26lt;stdio.h%26gt;





/*Ramesh Basic Salary*/


main ()


{


float DA,HRA;


float GS;





DA = 0.2;


HRA = 0.4;





/*Ramesh's Gross salary is sum total of DA and HRA*/;





GS = 10000*.2+.10000*4+10000;





printf("%f" , GS);


}





as WITH in my knowledge Gross salary = Net salary + DA+HRA;


GS = 10000 +10000*.2+10000*.4
Reply:#include %26lt;stdio.h%26gt;


void main ()


{


float DA,HRA;


float GS;





DA = 0.2;


HRA = 0.4;





/*Ramesh's Gross salary is sum total of DA and HRA*/;





GS = 10000*.2+.4;





printf("%f\n" , GS);


}
Reply:Do you HAVE to use the printf function in C++, or are you using it because you don't know about COUT?

easter cards

C program inside?

10 points to whoever can help me fix this.bear in mind I've absolutely no idea how rand works(that's the reason I'm here)





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


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


#define num 4


int main()


{


int a,b,c;


int vect[num],i;


int x,y,n;





printf(" Introduzca numero de jugadas ");


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


printf(" Introduzca monto del cual dispone ");


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





do{ y--; printf(" \nLe quedan %d jugadas\n",y);


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


vect[i]=rand() % 10;


a=vect[i];b=vect[i];c=vect[i];


}


if(a==b%26amp;%26amp;a==c){


x=2*x; printf(" Ganaste el triple\n ");


}


else if(a==b%26amp;%26amp;a!=c){


x=(3/2)*x; printf(" Ganaste el doble\n ");


}


else if(a=!b%26amp;%26amp;a==c){


x=(3/2)*x; printf(" Ganaste el doble\n ");


}


else if(b==c%26amp;%26amp;b!=a){


x=(3/2)*x; printf(" Ganaste el doble\n ");


}


else if(b!=c%26amp;%26amp;b!=a){


x=(x/2); printf(" Perdiste\n ");


}


while(y%26gt;0%26amp;%26amp;x%26gt;1);


system("pause");





}

C program inside?
I made some changes, and tried to add comments to explain what I did. Hopefully this helps some.








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


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





//needed for the line below where we seed


//the random number generator


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





#define num 4


int main()


{


int a,b,c;


int vect[num],i;


int x,y,n;





//otherwise it will generate exactly the


//same "random" numbers every time


srand(time(0));





printf(" Introduzca numero de jugadas ");


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


printf(" Introduzca monto del cual dispone ");


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





do{ y--; printf(" \nLe quedan %d jugadas\n",y);


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


vect[i]=rand() % 10;


//a, b, and c all ended up with the same value,


//the last random number you generated


}





//moved this outside the loop


//so they don't all have the same value


a = vect[0];


b = vect[1];


c = vect[2];





if(a==b%26amp;%26amp;a==c){


x=2*x; printf(" Ganaste el triple\n ");


}


else if(a==b%26amp;%26amp;a!=c){


x=(3/2)*x; printf(" Ganaste el doble\n ");


}


else if(a=!b%26amp;%26amp;a==c){


x=(3/2)*x; printf(" Ganaste el doble\n ");


}


else if(b==c%26amp;%26amp;b!=a){


x=(3/2)*x; printf(" Ganaste el doble\n ");


}


else if(b!=c%26amp;%26amp;b!=a){


x=(x/2); printf(" Perdiste\n ");


}


}//added a } that was missing


while(y%26gt;0%26amp;%26amp;x%26gt;1);


system("pause");





}
Reply:I am guessing you are asking about this line...





vect[i]=rand() % 10;





rand() returns a random number 0 to 2147483647





% 10 says divide by 10 and give me the remainder, so vect[i] value will get a value 0-9





you do have an error further down also...





3/2 is 1 in integer math. so x is just going to be x after each time you do this (3/2)*x, x is always same as when you started.





also your if statement is over complex...





if(a==b%26amp;%26amp;a==c){ /* if all are the same */


x=2*x; printf(" Ganaste el triple\n ");


}


else if(a==b || b==c || a==c){ /* else if 2 are the same */


x=(3*x)/2; printf(" Ganaste el doble\n ");


}


else { /* else none are the same */


x=(x/2); printf(" Perdiste\n ");


}





the else if you know all three are not equal already because they would have been found in the if...
Reply:rand() is a random number generator function. To make it really random, you need to call the srand function before.


C++ I have an error that I couldn't figure out T_T?

Here is my program :





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


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


void drain();


int main()


{


double x, y, Y, RE;


printf("\nEnter x: ");


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


y = pow(exp(x), 1.5);


printf("True value of exp(1.5*%.4f) = %lf", x, y);


char ch;


fflush(stdin);


printf("\n\nEnter a character 1-4 (0 to exit):\n");


ch = getchar();


switch(ch){


case 1:


printf("1 term(s) approximation"};


Y = pow(x, 0.)/1.;


printf("Approximate exp(1.5*%.4f) = ", x);


RE = 100 * (Y - y)/y;


printf("\nRelative error = %lf", RE);


break;


default:


printf("unrecognized operator");


}


}





.c: In function `main':


:17: error: parse error before '}' token








What should i do? .... thx so much

C++ I have an error that I couldn't figure out T_T?
well, thts easy, u see, u have defined main as returning an integer but u r not returning anything


check out the same program wid the corrections below





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


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


void drain();


int main()


{


double x, y, Y, RE;


printf("\nEnter x: ");


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


y = pow(exp(x), 1.5);


printf("True value of exp(1.5*%.4f) = %lf", x, y);


char ch;


fflush(stdin);


printf("\n\nEnter a character 1-4 (0 to exit):\n");


ch = getchar();


switch(ch){


case 1:


printf("1 term(s) approximation"};


Y = pow(x, 0.)/1.;


printf("Approximate exp(1.5*%.4f) = ", x);


RE = 100 * (Y - y)/y;


printf("\nRelative error = %lf", RE);


break;


default:


printf("unrecognized operator");


}


return(0);


}





if my solution was of help, gimme the best answer vote, pls
Reply:My vote goes to this line!


printf("1 term(s) approximation"};


It is line 17!





The end character should be ) NOT }





That was fun.
Reply:switch(ch) { %26lt;!-- put a space between (ch) and {


case 1:


printf("1 term(s) approximation"};


Y = pow(x, 0.)/1.; %26lt;!-- why do u have a point (.) after 1? if its a decimal put 1.0 and why do u havea period after 0?


printf("Approximate exp(1.5*%.4f) = ", x);


RE = 100 * (Y - y)/y;


printf("\nRelative error = %lf", RE);


break;


default:


printf("unrecognized operator");


C and data structure question pls help.....??

Which of the following cannot be implemented efficiently in Linear Linked List :


1.quicksort


2. Radix Sort


3. Polynomials


4. Insertion Sort


5. Binary Search





2. In binary search tree , n=nodes, h=height of tree.


What's complexity?


1. o(h)


2. o(n*h)


3. o(nLogn)


4. o(n*n)


5. None








C Programs


1. Printf("%d%d",i++,i++);


1. Compiler Dependent


2. 4 4


3. 4 3


4. 3 4


5. None of Above





3. what does it do?


void f(int n)


{


if(n%26gt;0)


{


if(A[i]%26gt;A[j])


swap();


}


else


f(n-1);


}


1. Swap


2. Sort in Ascending order


3. Sort in Descending order


4. Computes permutation





4. Given a Fibonacci function


f1=1;f2=1


fn=f(n-1)+f(n-2) which of the following is t is true?


1. Every Second element is even


2. Every third element is odd


3. The series increases monotonally


4. For n%26gt;2, fn=ceiling(1.6 * f(n-1))


5. None





Operating System


Where the root dir should be located?


1.Anywhere on System disk


2.Anywhe on Disk


3.In Main memory


4.At a fixed location on Disk

C and data structure question pls help.....??
1)--5


2)--4


- I think it's another question but i'm not sure so can't answer.


3)--1


4)--5


5)--3





Hope I helped.


Write a c program that inputs one five digit number, separtes the number into its individual digits.?

i need to use integer division and the remainder operation. eg. if i type 42139 it should look like 4 2 1 3 9. help please!!!


x=52


52%10=2


52-2=50


50/10=5





117%100=17


117-17=100


100/100=1


below is my code so far


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


int main()


{


int a,b,c,d,e;


printf("enter 5 single digits\n");


scanf("%f%f%f%f%f", %26amp;a,%26amp;b,%26amp;c,%26amp;d,%26amp;e,)


a=%f





}

Write a c program that inputs one five digit number, separtes the number into its individual digits.?
Since you know it is 5 digits long you could:





1. Divide the input by 10000 (notice its 5 digits long as well). The reason being that in computers dividing integers always returns an integer then your result will be a whole # and so e.g., 42139 / 10000 = "4"





2. Subtract: your answer from #1 which is 1st multiplied by 10000 from the original 5-digit input e.g. 42139 - 40000 = 2139





3. Now, divide 2139 by 1000 (notice its 4 digits)...this gives you the answer of: "2"





2. Subtract: your answer from #3 which is 1st multiplied by 1000 from the 4-digit input mentioned in #2 e.g. 2139 - 2000 = 139





3. and so on....





It should be noted that the modulus (remainder operator could be used instead where i was multipying the result with the 10^x in the steps above...it was just merely preference for me)
Reply:Don't want to do your homework, but your code won't work, you need %d instead of %f. But as another poster said, why not scan it as a string and output it as chars?





char ins[80];


int c;





printf("enter a five digit number: ");


scanf("%s", ins); /* this will break if they enter %26gt; 80 */


for(c = 0; c %26lt; 5; c++){


putchar(ins[c]);


putchar(' '); /* that's a space between the quote marks */


}


putchar('\n');
Reply:I would read the number in as a string and then using the substr functions, i would retrieve each digit.





Good luck.

brenda song

In Linux c programming, can we read a single charecter into a char variable without pressing enter key ?

I wrote the following program but I have to press enter key to get read the value into the variable.


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


main()


{


char c;


while(c!='n')


{


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


fflush(stdin);


printf("ok");


}


}


Is there any solution for this? Why?

In Linux c programming, can we read a single charecter into a char variable without pressing enter key ?
Use curses library. Its a wonderful library for exactly what you are looking for. Using this library you can handle keystrokes i.e. a char is trapped as soon as it is pressed, you dont have to wait for enter key press.





if curses.h is not availble in your machine, then re-run Linux setup, select custom libraries, there you will find ncurses library.





You get more info at:


http://www.gnu.org/software/ncurses/ncur...


http://www.unet.univie.ac.at/aix/aixprgg...


http://www.gmonline.demon.co.uk/cscene/C... -%26gt; great one to start off with





Good luck.
Reply:use the getch() function if you want to read a single char and not have it written to the console. If you want to read a char and have it written to the console then use getchar(). Neither function have any arguments to deal with and they only return characters from the keyboard, if either function returns zero it means that multiple keys have been pressed like Alt, if it dose return zero then you have to call the function again to find out what non-graphical keys were pressed. getch and getchar may not appear in your library of functions but it is in mine in the conio header.
Reply:Have you tried kbhit();


Need basic C programming help.?

Hey, newbie programmer here. I've been trying to program something and I'm having a little trouble.





I needed to ask for user input for the amount of rows in the triangle. The number of rows can only be odd numbers and less than 10.


The output should look like





*





**





***





**





*





For a 5 row triangle. I got the input thing down I think but I can't find out how to put the * in that pattern. I'm trying to use a nested for loop, I'm I going at it with the wrong loop? The spaces need to be there too.





Here is my code, it's not done, I couldn't get it to work for 3 so I stopped.





printf("How many rows do you want?\n");


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





switch(c){


case 0:


printf("You can't have 0 rows\n");


break;


case 1:


printf("*")


break;


case 2:


printf("Your number must be an odd number\n");


break;


case 3:


for(counter=1; counter%26lt;=c; counter++){


for(a=1; a%26lt;=counter; a++){


printf("*");}


printf("\n\n");


break;





I'm sure I am just stupid but I can't figure how to make the triangle decrease in *.

Need basic C programming help.?
Looking at your code, it will not handle anything over 3 rows.





My advice would be to capture the users input. Ensure that it is not 0., if it is, exit the routine.





Then use a modulus operator with the value of 2 to ensure an odd number. If it is an even number, exit the routine.





Find the midway point. Add 1 to c and then divide by 2. For instance if c is 5, add 1 to that to get 6 and divide by 2 to get a midway point of 3. Then using the for loop like you currently have set up (with the nested loop) loop until counter %26lt;= to the midway point. Once that loop structure is done executing have the program execute another loop sequence very similar to the first one (with the included nested loop) but have the loop set up as:


for (counter=midwaypoint-1;counter %26gt;0;counter--)





This way you will create all of the rows as required.
Reply:Hi I wont get into the way you validate that the user has entered an odd number but I'll show you how to draw the decreasing side:





c=5; /* or any odd number 3, 5, 7, 9 etc */





/* start at 1 and draw the increasing side */


for (counter=1; counter%26lt;=c; counter++)


{


for (a=1; a%26lt;=counter; a++)


{


printf("*");


}





printf("\n\n");


}





/*


** counter should now be 1 over the rows eg counter = c+1


** take off 2 so that the largest row isnt drawn again


*/


counter = counter - 2;





/*


** now draw decreasing side but decrementing it in a loop


** until it hits 1


*/


for(; counter%26gt;=1; counter--)


{


/* This code is the same as above */


for(a=1; a%26lt;=counter; a++)


{


printf("*");


}





printf("\n\n");


}








Good luck.
Reply:A couple of things ..





to check for validity of input





int c;


...


if( (c/2 * 2 ==c) || (c%26gt;9) ) .....error, ask for new input





to go backwards just run your loop backward





for(counter = c-1; counter%26gt;=1; counter--)
Reply:Not stupid - just learning...





Have a try at this:


1) After the user enters a number, make sure it is valid. You say only odd numbers between 1 and 10. Note that odd numbers when divided by two will give a remainder. Thus, the MOD() function can help in determining if a number is odd or not. (and eliminate the need to a case statement)





2) Assuming the number is good, set up three FOR loops


a) the first is as you have it now using counter


b) the second goes from 1 to half of your number or (5/2)+1


Each time through, print an asterisk


c) the third goes from half the number to 1 (5/2)


Each time through, print an asterisk





(There's another way to do the above, but since you're learning, the above way is easier to understand for now.)


Fellow c programmers i need HELP!!! with my program?

i need to remove the return statements from my if statment and make the program not continue after the error message. i also need to make else statements that just continue the program.....thank you





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


int main( )


{


float a,b,c,d,e,f;


d=40;


e=1;


f=6.75;


printf("***WAGE CALCULATOR***\n\n") ;


printf("How many hours did you work this week?: ") ;


scanf("%f",%26amp;a);


if (a%26gt;d) {


printf("\nError more then 40 hour.\n",a);


return 0;


}


printf("\nWhat is your hourly wage?: ") ;


scanf("%f",%26amp;b);


if (b%26lt;f) {


printf("\n ERROR value under 6.75 not accepted");


return 1;


}


c=a*b;


printf("\nyour gross salary is: $%f\n",c);











return ( );





}

Fellow c programmers i need HELP!!! with my program?
PROGRAMMING TIP...





WrItE yOuR cODE sO iT Is eASy tO rEaD!!!





Thus changes to be made are all that much easier.





The tab format is lost in the edit box here,


so just align the { } brackets to see the nested if-else statements.


Help with my C program. How do I ask the user whether they want to start again?

What line of code would I use to ask the user if they wanted to start over from the beginning? I want to put this line of code at the end of the program.





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





int main()


{


float e, d, a, b, c;


d=40;


e=6.25;


printf("Wage Calculater\n");


Start:


printf("\nEnter the amount of hours worked: ");


scanf("%f",%26amp;a);


if (a%26gt;d){


printf("\n\n ***INVALID***\n\n");


printf("Only 40 hours are possible in a week");


goto Start;


return 1;


}


Mid:


printf("\nNow enter your hourly rate: ");


scanf("%f",%26amp;b);


if (b%26lt;e){


printf("\n\n ***INVALID***\n\n");


printf("Entered value was less then minimum wage\n");


goto Mid;


return 1;


}


c=a*b;


printf("\nYour salary for this week is:\n");


printf(" \n ***%f***\n",c);


system ("pause");


return 0;


}

Help with my C program. How do I ask the user whether they want to start again?
do a looping statement..





do{


/* you should place your codes here that you want to be repeated*/


do{


printf("do you want to try again? Y/N");


ans = getch();


}while(toupper(ans) != 'Y' %26amp;%26amp; toupper(ans) != 'N');


}while (toupper(ans)=='Y');





//make a variable ans
Reply:C has a powerful feature called recursion. (You may know that).





In the end of the program add


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


fflush(stdin); /* this is required. try without this */


opt = getch(); /* you must declare char opt */


if toupper(opt) = 'Y' /* #include %26lt;ctype.h%26gt; */


main(); /* this is recursion. main() is called inside main() */





Why do you use goto statements? They cause the system to abruptly jump. Use do while instead. (This loop executes at least once. If the answer matches the criteria, control is terminated out of the loop. Otherwise it loops again)

bouquet

Why print 144 in output(Turbo c)?

void main(){


unsigned char c;


c = 100 * 4;


printf("%d",c);


}

Why print 144 in output(Turbo c)?
A 'char' is a byte-sized variable. An unsigned byte can only contain a value from 0 to 255. A signed byte can only contain a value from 127 to -128.


The reason you got 144 is because 144 is the lower byte of the number 400. If you declared the variable 'c' as an integer (a two byte variable in 16 bit compilers), then you would have gotten the number 400.


In hexadecimal, the number 400 is this:


01 90


If you convert only the lower 90 byte to decimal, you get 144. So, you see, when you assigned 'c' to be equal to 400, the compiler couldn't fit the whole number into the byte, so it just put the lower byte of the number 400 into the 'c' variable.
Reply:because unsigned char c


composed of 8 bits


100*4=400


400 in binary is 1 1001 0000


unsigned char only takes 1001 0000


it only take 8 bits


1001 0000 in decimal is 144


C mysteries??

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


void main()


{


printf("%d%c");


}





the output of te program is


0 and X


how is it possible??





if you have programs like this sort ,plzz write in!i would love 2 know more!!!

C mysteries??
In your printf("%d%c");


you do not specify any variables or data to be printed.


Printf() "pretends" there is data anyway and prints it out (what the 0 and X are is whatever is on the stack at the time - return addresses usually).





try printf("%d%c", 123, 88 );
Reply:I think it can print anything. Since you have not specifed the format string properly, and these are the (were) major causes of vulnerability in server applications.


Printf() function will first read string and understand the format what to print and then will go on to read the data to print in that exact format specified. Since you have not provided the data/variable it will go in to the next address (pointer) to pick the data and for that it is going to print the garbage which is present there at that time.


I think its not necessary that it print 0 and X every time, across every platform/c-compiler.


Here is a question in c. can any body tell me logic behind this program?

main(){


float a = 0.7;


if(a%26lt;0.7){


printf("is c working");


}


else


printf("s, it's working");


getch();


}


normally result should be else block("s, it's working") but the result is "is c working"


and it's only for 0.7 value but not for the other values.


Is it the fault in c or any logic behind this





can any one tell me the reason behind this extraordinary program.

Here is a question in c. can any body tell me logic behind this program?
It is actually a bit tricky, but the problem is that 0.7 is not a float and thus the expression is not evaluating as it should.





If you change the statement to


if( a %26lt; (float)0.7 )


then it will work as it should.





The other way around this is to just create a new float and assign the value 0.7 to it, then it will definitely work correctly.
Reply:The problem is in how the compiler "casts" the value. Make an explicit cast and it will always work.
Reply:It is possibly comparison of float with the double type in (a%26lt;0.7). You might want to use the "fabs" function during comparison. You might also want to use the suffix "f" to both the 0.7s and see how it behaves.
Reply:Floats in C or any other programming language are not exact. Even if you set the value in a to 0.7 the computer will convert it to 0.7 +or- .0000000000001 or something similiar. Add a line to print value of a to see what it is and then you will understand floating point precision.





This is an issue that all programmers face because processors do everything in interger format.