Friday, September 9, 2011

Difference between puts and printf for strings



Expand Post »
Hello when Im trying to learn strncpy function, I copied a part of string to another char array, but it gave me different results when I used puts and printf functions. Can anyone tell me why such difference occurs? I guess its about the last terminating NULL character, but Im not sure at all. Here is the code :
1.            
2.            #include <stdio.h>
3.            #include <string.h>
4.            int main()
5.            {
6.                    char a[] = "barbara dickens";
7.                    char b[8];
8.                    strncpy(b,a,7);
9.                    puts(b);
10.                printf("%s", b);
11.        
12.               return 0;
13.        }
puts function prints barbara and printf function prints barbar,


When printing a string (no format specifiers), the difference between puts and printf is that printf probably does more work for the same result. The reason is because printf needs to check for format specifiers(%d,%s.%f etc) while puts simply passes each character on to putchar. But your problem isn't related to which function you use for display.

>char b[8];
>strncpy(b,a,7);
>puts(b);



DIFFERENCE B/W PUTS AND COUT:


1 - puts is an ANSI C function defined in the <stdio.h> header
2 - cout is not a function: it's a stream, associated to a file. When you do something like:
cout << "Hello" << endl;
You are using operator << (operator 'send to', which is a function, but written in C++, so unlike puts, it's Object-Oriented) : you are sending the string "Hello" to the stream cout, which is analogous to C's stdout.
3 - Same for getline and cin, except that getline is redefined in C++'s <iostream> header, so you need to be careful.

No comments:

Post a Comment