Reputation: 31397
Code copy string in C
#include <stdio.h>
char *copyString(char *,char *);
void main()
{
char *first = (char *)calloc(sizeof(char),10);
char *second = (char *)calloc(sizeof(char),10);
printf("Enter first string:\t");
scanf("%s",first);
printf("%s",copyString(first,second));
}
char *copyString(char *a,char *b)
{
int i=0;
while(*(a+i)!='\0')
{
*(b+i)=*(a+i);
i++;
}
*(b+i)='\0';
return b;
}
Case 1:
Input : Hello
Output : Hello
Case 2:
Input : Hello World
Output : Hello
So, my question is whether space
is considered as newline/null
?? Because, in second case, it shows like this..
Upvotes: 1
Views: 6678
Reputation: 25695
scanf()
stops reading after the first whitespace by default. Use fgets()
or gets()
[unsafe]. With regards to why it is this way, you might want to read the POSIX pages here: http://www.unix.com/man-page/POSIX/3posix/scanf/ and ISO C standards here: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1124.pdf. It has a lengthy description on how scanf()
and fscanf()
(and all other standard C functions) should work. These are generally followed guidelines on how functions in C library should work.
All compilers strive hard to create POSIX compliant standard-c libraries that work the same across most UNIX'ish platforms.
The standard C functions are actually defined here: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1124.pdf
Upvotes: 2
Reputation: 112
use #include and utilize this function strcpy of string.h lib. following is the example:
strcpy(first, second);
This should run fine.
Upvotes: 0
Reputation: 1282
The scanf function here will read input until it encounters whitespace. You will need to implement a readline function.
Upvotes: 0
Reputation: 15644
Your scanf
is scanning just one string for two strings to be scanned you should write:
scanf("%s %s",first,second);
Similarly for more strings to be scanned you should do like this that is giving as many %s
as many strings you want to scan.
Upvotes: 0
Reputation: 17312
As suggested scanf
stops at the first whitespace, you could use fgets
instead to read the whole line. And when you get that working allocate more space, because "Hello World" is 12 bytes not 10.
Upvotes: 1
Reputation: 121377
It's because stops reading after whitespace when you input it the string. So you actaully only have "Hello"
in your first
string, not "Hello world"
.
Use fgets()
to read the whole line.
Upvotes: 1
Reputation: 23699
By default, scanf
stops reading the standard input stream when a space character ' '
is encountered. To fix it, you can use a scanset.
scanf("%[^\n]", first);
Upvotes: 9