Question

C Language! Please, comment what each line of code does in the code below and answer...

C Language!

Please, comment what each line of code does in the code below and answer this question: (sentence is fine)


1. Aside from pressing ctrl-(d/z) at the beginning of a line causing the getnchar() function to return NULL, is there any way to enter less than 9 characters?

Code:

void exer1(void)
{
   char input[LEN];
   char *check;
getchar(); // Clearing character buffer.
printf("Please enter 9 characters: "); // Prompting the user to enter
// a specific input.
  
   check = getnchar(input, LEN - 1);
   if (check == NULL)
       puts("Input failed.");
   else
       puts(input);
   puts("Done.\n");

}

char * getnchar(char * str, int n)
{
   int i;
   int ch;

   for (i = 0; i < n; i++)
   {
       ch = getchar();
       if (ch != EOF)
           str[i] = ch;
       else
           break;
   }
   if (ch == EOF)
       return NULL;
   else
   {
       str[i] = '\0';
       return str;
   }
}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

The code is given below which is properly commented line by line:

void exer1(void)
{
char input[LEN];/* input char array of size of LEN*/
char *check;/* pointer to char*/
getchar(); // Clearing character buffer.
printf("Please enter 9 characters: "); // Prompting the user to enter
// a specific input.
  
check = getnchar(input, LEN - 1);/* call to getnchar()*/
if (check == NULL)/* if NULL is in check*/
puts("Input failed.");/* message to display*/
else
puts(input);/* Display what is in input array */
puts("Done.\n");/*message to display*/

}
char * getnchar(char * str, int n)/* 'str' as a pointer to char array and 'n' as length*/
{
int i;/* integer variable declaration*/
int ch;/*char variable declaration*/

  
for (i = 0; i < n; i++)/*loops as long as value of i is less than n */
{
ch = getchar();/* reads a single char*/


if (ch != EOF)/* check to see if EOF generated by ctrl+d/z is not in char ch */


str[i] = ch; /* stores that character in str array at index i*/
else
break; /* breaks from loop if the character read is EOF generated by ctrl+d/z */
}
  
  
if (ch == EOF)/* check to see if EOF generated by ctrl+d/z is in char ch */

return NULL; /*returns NULL when ctrl+d/z pressed at beginning*/
else
{
str[i] = '\0';/* terminates the string str with string terminator char which is a '\0' */
return str; /*returns the str array*/
}
}

/**************************/
Aside from pressing ctrl-(d/z) at the beginning of a line causing the getnchar() function to return NULL, yes there is a way to enter less than 9 chars: just press ENTER key at beginning or when finished typing.

A complete modified code for this purpose with proper execution is given below:

/*
* File: main.c
*
*/

#include <stdio.h>
#include <stdlib.h>
#define LEN 10
/*
*
*/

void exer1(void); /*prototype declaration*/
char * getnchar(char * str, int n);/*prototype declaration*/
/*main() definition*/
int main() {
exer1(); /*call to exer1()*/

return (0);/* return on successful exit*/
}
/* exer1() definition*/
void exer1(void)
{
char input[LEN];/* input char array of size of LEN*/
char *check;/* pointer to char*/
getchar(); // Clearing character buffer.
printf("Please enter 9 characters: "); // Prompting the user to enter
// a specific input.
  
check = getnchar(input, LEN - 1);/* call to getnchar()*/
if (check == NULL)/* if NULL is in check*/
puts("Input failed.");/* message to display*/
else
puts(input);/* Display what is in input array */
puts("Done.\n");/*message to display*/

}
/* getnchar() definition*/
char * getnchar(char * str, int n)/* 'str' as a pointer to char array and 'n' as length*/
{
int i;/* integer variable declaration*/
int ch;/*char variable declaration*/

  
for (i = 0; i < n; i++)/*loops as long as value of i is less than n */
{
ch = getchar();/* reads a single char*/
/* I've commented the below line*/
/*
if (ch != EOF)
*/
if (ch != '\n')/* modified code to check if the character read is not ENTER key pressed */
str[i] = ch; /* stores that character in str array at index i*/
else
break; /* breaks from loop if the character read is ENTER key pressed*/
}
/* I've commented the below line*/
/*
if (ch == EOF)
*/
if (ch =='\n'&& i==0)/* modified code to check if ENTER key pressed is detected at beginning*/
return NULL; /*returns NULL when ENTER key is pressed at beginning*/
else
{
str[i] = '\0';/* terminates the string str with string terminator char which is a '\0' */
return str; /*returns the str array*/
}
}
/***********************/

Source code screen shot is given below:

Output screen shot is given below:

Add a comment
Know the answer?
Add Answer to:
C Language! Please, comment what each line of code does in the code below and answer...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Write a function that can return the length of a string in C language. Please leave...

    Write a function that can return the length of a string in C language. Please leave comments to explain the code and verify that it runs properly... Example: Input String: China The length of the string is 5. #include <stdio.h> int length(char * p) {     /write your code here } main(){     int len;     char str[20];     printf("Input string:");     scanf("%s", str);     len = length(str);     printf("The length of string is %d. ", len);     getchar();    ...

  • Write a C program that takes two sets of characters entered by the user and merge...

    Write a C program that takes two sets of characters entered by the user and merge them character by character. Enter the first set of characters: dfn h ate Enter the second set of characters: eedtecsl Output: defend the castle Your program should include the following function: void merge(char *s3, char *s1, char *s2); The function expects s3 to point to a string containing a string that combines s1 and s2 letter by letter. The first set might be longer...

  • Write a program that replace repeated three characters in a string by the character followed by 3...

    Write a program that replace repeated three characters in a string by the character followed by 3. For example, the string aabccccaaabbbbcc would become aabc3ca3b3cc. When there are more than three repeated characters, the first three characters will be replaced by the character followed by 3. You can assume the string has only lowercase letters (a-z). Your program should include the following function: void replace(char *str, char *replaced); Your program should include the following function: void replace(char *str, char *replaced);...

  • rewrite this c code in python #include <iostream> using std::cout; using std::cin; using std::endl; int charClass;...

    rewrite this c code in python #include <iostream> using std::cout; using std::cin; using std::endl; int charClass; char lexeme[100]; char str[200]; char nextChar; const int LETTER = 0; const int DIGIT = 1; const int UNKNOWN = -1; const int OPAREN = 2; const int CPAREN = 3; const int PLUS = 4; const int MINUS = 5; const int MUL = 6; const int DIV = 7; const int ID_CODE = 100; const int PLUS_CODE = 101; const int MINUS_CODE...

  • #include <stdio.h> #include <stdlib.h> #include <string.h> #include<ctype.h> #define MAX_LEN 255 int numWords(char *str); int numDigit(char *str);...

    #include <stdio.h> #include <stdlib.h> #include <string.h> #include<ctype.h> #define MAX_LEN 255 int numWords(char *str); int numDigit(char *str); int numUppltr(char *str); int numLwrltr(char *str); int punChar(char *str); char*readString(char *str); int main() { char givString[MAX_LEN]; puts("Enter your string(Max 255 characters):"); //readString(givString); gets(givString); printf("\nnumber of words :%d",numWords(givString)); printf("\nnumber of uppercase letters %d",numUppltr(givString)); printf("\nnumber of lowercase letters %d",numLwrltr(givString)); printf("\nnumber of punctuations %d\n",punChar(givString)); printf("\nnumber of digits:%d\n",numDigit(givString)); system("pause"); return 0; } char *readString(char *str) { int ch, i=0; while((ch=getchar())!=EOF && ch!='\n') { if(i) { str[i]=ch; i++; }...

  • Convert C to C++ I need these 4 C file code convert to C++. Please Convert...

    Convert C to C++ I need these 4 C file code convert to C++. Please Convert it to C++ //////first C file: Wunzip.c #include int main(int argc, char* argv[]) { if(argc ==1){ printf("wunzip: file1 [file2 ...]\n"); return 1; } else{ for(int i =1; i< argc;i++){ int num=-1; int numout=-1; int c; int c1;    FILE* file = fopen(argv[i],"rb"); if(file == NULL){ printf("Cannot Open File\n"); return 1; } else{ while(numout != 0){    numout = fread(&num, sizeof(int), 1, file);    c...

  • I need assistance with this code. Is there any way I can create this stack class (dealing with infix to postfix then postfix evaluation) without utilizing <stdio.h> and <math.h>? ________...

    I need assistance with this code. Is there any way I can create this stack class (dealing with infix to postfix then postfix evaluation) without utilizing <stdio.h> and <math.h>? ____________________________________________________________________________________________ C++ Program: #include <iostream> #include <string> #include <stdio.h> #include <math.h> using namespace std; //Stack class class STACK { private: char *str; int N; public: //Constructor STACK(int maxN) { str = new char[maxN]; N = -1; } //Function that checks for empty int empty() { return (N == -1); } //Push...

  • You must use C Language. The Main Objective: Make the first and last name ALL CAPITALS...

    You must use C Language. The Main Objective: Make the first and last name ALL CAPITALS even if the user types in lower case letters. Lastly, flip the first name and last name around. So: HEIDI, HATFIELD to HATFIELD, HEIDI. (PLEASE uppercase all the letters) End Goal: HATFIELD, HEIDI KAISER, RUSSELL LIPSHUTZ, HOWARD PENKERT, DAWN WRIGHT, ELIZABETH Please use this reference below, to fix the code given. Code given is below, I want the user to be able to enter...

  • Using C(89). A fashion retailer has decided to provide discount codes to teachers and students during...

    Using C(89). A fashion retailer has decided to provide discount codes to teachers and students during a promotional event. The first step is to verify the teacher/student status of people requesting discount code by their email addresses. They will check if the email addresses end with ".edu" and find the domain name if it does before further verification. Write a program to find the domain name of an email address if the domain name ends with .edu. The program displays...

  • Help me to fix this code in C language. This code converts infix expressions to postfix and then evaluate the expression...

    Help me to fix this code in C language. This code converts infix expressions to postfix and then evaluate the expression. Right now, it works with single digits. I need to modify it so that it can evaluate expressions with also 2 digits, example: (60+82)%72. Additionally I need to display an error when the parenthesis don't match like (89+8(. I have muted some line that would print the postfix expression with a space like: 22 8 + when the input...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT