Showing posts with label Data From User. Show all posts
Showing posts with label Data From User. Show all posts

C Program that prompts the user to input a string, (whitespaces allowed)

How to Write a program that prompts the user to input a string, (whitespaces allowed)
Add code to:
Step 1: allocate memory for the string
Step 2: Scanf the string from the user
Step 3: Write a function to calculate the length of the string.
            int length(char name[]);Â


Solution:

/*Write a program that prompts the user to input a string, (whitespaces allowed)
Add code to:

step1: allocate memory for the string
step2: Scanf the string from the user
step3: Write a function to calculate the length of the string.
int length(char name[]);Â


*/
#include<stdio.h>
#define SIZE 41

int main()
{ 
 //Define student name
 char name[SIZE];
 printf("Please enter your name:");
 scanf("%[^\n]",name);
 
 printf("The length of the name is %d",length(name));
 getch();
}

int length(char name[])
{
 int i,result=0;
 for(i=0;name[i]!='\0';i++)
  result++;
  
 return result;

}

C Program to accept data from user store that data into text file

How to write a C program to accept data from user store that data into text file in C Programming Language ?


Solution:
/*write a c program to accept data from user store that data into text file */
#include<stdio.h>
#include<conio.h>
void main()
{
char str[60];
FILE *fp;
clrscr();
printf("\nenter the string:");
gets(str);
fp=fopen("peer.txt","w");
if(fp==NULL)
{
printf("connot open");
exit();
}
fputs(str,fp);
getch();
}
/*
enter the string:i am not an intelligent                                      
                                                                             
Type EXIT to return to Turbo C++. . .Microsoft(R) Windows DOS                
(C)Copyright Microsoft Corp 1990-2001.                                        
                                                                             
C:\TC\BIN>type peer.txt                                                      
i am not an intelligent                                                      
C:\TC\BIN>exit                                                                
*/