C Language Tutorials by Ghulam Murtaza Dahar - HTML preview

PLEASE NOTE: This is an HTML preview only and some elements such as links or page numbers may be incorrect.
Download the book in PDF, ePub, Kindle for a complete version.

Output

Enter name: Dennis Ritchie

Your name is Dennis.

Here, program will ignore Ritchie because, scanf() function takes only string before the white space.

Reading a line of text

C program to read line of text manually.

#include <stdio.h>

int main(){

char name[30],ch;

int i=0;

printf("Enter name: ");

while(ch!='\n') // terminates if user hit enter

{

ch=getchar();

name[i]=ch;

i++;

}

name[i]='\0'; // inserting null character at end

printf("Name: %s",name);

return 0;

}

This process to take string is tedious. There are predefined functions gets() and puts in C language to read and display string respectively.

int main(){

char name[30];

printf("Enter name: ");

gets(name); //Function to read string from user.

printf("Name: ");

puts(name); //Function to display string.

return 0;

}

Both, the above program has same output below: