Hello to all.... I have a problem in my code. Well I have done a program (an exercise) that it takes your name (first + last) for instance you may have something like :
Code:
Enter your name: Bill Gates
And the program will produce the following output :
The code is :
Code:
#include <stdio.h>
#include <string.h> // strcat()
#include <ctype.h>
#define STR_LEN 80
void reverse_name(char *);
void read_line( char * , int );
int main(void)
{
char name[STR_LEN+1] = {'\0'};
printf("Enter your name: ");
read_line(name , STR_LEN);
puts(name);
reverse_name(name);
puts(name);
return 0;
}
void read_line(char name[] , int n)
{
int ch , i=0;
while( (ch = getchar()) != '\n' ) {
if(i < n )
name[i++] = ch;
}
name[i] = '\0';
}
void reverse_name(char *name)
{
char *p = name, first_letter[1+1];
while (*p == ' ') p++; // Skip blanks in the beginning
first_letter[0] = *p; // save the 1st character of the first name
while (*p != ' ') p++; //
while (*p == ' ') p++; // skip blanks between first and last name
for (; *p != ' ' && *p; p++, name++)
*name = *p; // Copy last name into first name
*name = '\0';
strcat(name, ", "); // Gates,
strcat(name, first_letter); // Gates, B
strcat(name, "."); // Gates, B.
}
If I don't use the first call of puts function in my main... the result of the program is undefined for example....
Code:
printf("Enter your name: ");
read_line(name , STR_LEN);
///puts(name);
reverse_name(name);
puts(name);
If I use the first call of puts ... the result is regular. Why??????????
I can't understand.... where is the problem ?