Thursday, July 30, 2009

C++ Programming help please?

Whenever I used scanf and printf in my Program, it compiles and runs successfully but during running when inputting data it doesnt respond and halts, but whenever I used cout%26lt;%26lt; and cin%26gt;%26gt; it responds and runs with no problem, Whats the most possible reason for that?


Im using DEV-C++ compiler

C++ Programming help please?
well... the printf, scanf function are C language instructions , not C ++ instructions .. that's why it doesn't work I think ... if you used another C compiler .. it may work
Reply:It doesn't matter if you use cout or printf in C++, you can do both if you include the right header files. Anyway, the reason for this could be many, you need to post the code to get a straight answer.
Reply:If you are using C++, you will want to use std::cin and std::cout


instead of scanf and printf.





As for your problem, Are you sure you are terminating your scanf program correctly? Please post the code so we can look.





Roland A, Please see the Design And Evolution of C++.
Reply:Actually, the answer above isn't, strictly speaking, correct.





C++ _is_ c, but with extensions.





scanf (and fscanf) are useful for reading data that you know is formatted (that's what the f stands for) in a precise way.





These statements:


int n1, n2;


scanf("%d %d\n", %26amp;n1, %26amp;n2);





will look for a couple of numbers separated by a space and terminated with a newline, and store the numbers into n1 and n2. Notice that the "enter" key does not generate a newline character.


Strange as it seems, to end this scanf call, you need to press ^N (control - n). Go figure.








If you're reading sequences of ASCII characters, I recommend using fgets:





char buffer[1024];


fgets(buffer, 1024, stdin);





stay away from gets() -- it's a dangerous input function.


Note that fgets stores the newline character in the string it reads. You can kill the newline (if you don't want it) with:





char *cp=strchr(buffer,'\n');


if (cp) *cp=0;





Those lines will replace the newline (if it exists) with a null, terminating the string.





To use fgets() you need to #include %26lt;stdio.h%26gt;


Note that stdin is the pre-defined name of the standard input stream.





To use strchr() you'll need to #include %26lt;string.h%26gt;





If you want to define your input buffer using a more "C++" style, you could do:


char *buffer=new char[1024];


This ensures that when the variable goes out of scope, the memory it points to will be automatically freed.











Hope this helps.


No comments:

Post a Comment