I need to write a C program using getchar function to read a string from the use
ID: 3546454 • Letter: I
Question
I need to write a C program using getchar function to read a string from the user. One advantage of using getchar function is it allows to read white space (while scanf does not).Read a string from the user and clean the string such that the cleaned string contain alphabets only (all upper case as shown in the example below.)
Example
Input string is asdas#@$21 REJye&*(iiL efwg
Cleaned string is ASDASREJYEIILEFWG
Implement following function for the pre-lab.
void readInput(char *): This function takes a character pointer (pointer to an empty array), use the
getchar function to read string from the user. Use a newline character ' ' as a termination condition for
the loop for the getchar function.
void cleanString(char * , char *): This function takes the input string from the user and clean the
input string as shown in the example above. This function takes two character pointers, a character pointer
(holding the starting address of the input string ) and a pointer (holding the starting address of empty
array).Store the cleaned string using the second pointer. Use functions like strlen(), isalpha(), toupper()
etc. from the string.h and the ctype.h libraries to clean the input string.
main():Call the above two functions to read a string from the user and get a "cleaned" string.
Note
1. To store strings create size 100 character 1D arrays in the main.
2. Use getchar function.
3. Use only pointer notation and pointer arithmetic to implement the assignment.
Sample output
Characters in bold are input from the user.
[sm3z5@babbage lab10]$ ./a.out
Enter the input string: co#%@M][pu?>terS+-cie@#Nce
Input string is co#%@M][pu?>terS+-cie@#Nce@
Cleaned string is COMPUTERSCIENCE
[sm3z5@babbage lab10]$ ./a.out
Enter the input string: asdas#@$21 REJye&*(iiL efwg
Input string is asdas#@$21 REJye&*(iiL efwg
Cleaned string is ASDASREJYEIILEFWG
[sm3z5@babbage lab10]$ ./a.out
Enter the input string: OIUi#@$EBRF t45./,05}sdoe -0=8[-0{kjgry
Input string is OIUi#@$EBRF t45./,05}sdoe -0=8[-0{kjgry
Cleaned string is OIUIEBRFTSDOEKJGRY
Explanation / Answer
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void readInput(char *string)
{
int i = 0;
char c;
while(1){
c = getchar();
if( c == ' '){
*string = ''; //null terminate
return;
}
//string is too large, only save 99 spots + null terminate the string
if(i == 99){
string[99] = '';
}
*string = c;
string++;
i++;
}
}
void cleanString(char *original, char *cleaned)
{
char c;
int i, length;
length = strlen(original);
for(i = 0; i < length; i++){
c = *original;
if(isalpha(c)){
*cleaned = toupper(c);
cleaned++;
}
original++;
}
*cleaned = '';
}
int main()
{
char string[100];
char clean[100];
printf("Enter the input string: ");
readInput(string);
printf("Input string is %s ", string);
cleanString(string,clean);
printf("Cleaned string is %s ", clean);
return 0;
}