SlideShare a Scribd company logo
1 of 10
Download to read offline
The Task
For this assignment you will write a rudimentary text editor that allows the user to edit 5 lines of
text, where each line is no longer than 80 characters. The editor should allow the user to
continue editing as long as desired and should print the current state of the edit buffer after each
edit.
The editor is a 'line editor' in that the user must edit one line at a time. The user can specify
which line should be edited by choosing a line number from a menu.
The only two editing operations possible are to replace an entire line with a new line, or to
replace a substring in the line with a new substring.
Musts
The program should not accept incorrect menu choices from the user. If the user creates a string
that is longer than 80 characters the string should be truncated to fit the 80 character limit. The
program should simply make no changes if the user tries to replace a substring that does not exist
in the string.
Your program must use functions. Some functions are required, but you may make other
functions as you see fit. You may not change the name, return type, or the parameter list types
for required functions.
Required Function One
int replaceInString(char[] original, char[] substring, char[] replace);
This function causes the original string to be modified such that the first occurrence of substring
is removed from the original string and the contents of replace are inserted in its place.
replaceInString calls findSubString and insertString. The function returns 0 if the operation
fails and 1 if the operation is successful.
Required Function Two:
int findSubString(char[] original, char[] toFind);
This function finds the first occurrence of toFind in original and returns an integer representing
the index of the first element of the toFind substring in original. For example if toFind was 'cat'
and original was 'thundercat' the function would return 7 since the begining of 'cat' in
'thundercat' is position 7. If the function does not find a substring it should return -1
note: do not use existing substring functions such as strstr as a solution for this function. Solve
the algorithm yourself. You may use basic string functions such as strlen and strcat.
Required Function Three:
int insertString(char[] original, int start, int length, char[] toInsert);
This function replaces the contents of original with the following sequence of characters:
the characters from original up to position start-
the characters from toInsert
the characters from original starting at the character immediately after length.
Solution
#include
#include
#define ROW_LENTH 81
#define NUM_ROWS 5
void replaceLine(char line[]);
void printText(char text[][ROW_LENTH]);
int readFile(char filePath[], char text[][ROW_LENTH]);
int writeFile(char filePath[], char text[][ROW_LENTH]);
void removeTrailingHardReturn(char line[]);
void flushBuffer();
int getLine();
int replaceInString(char original[], char substring[], char replace[]);
int findSubString(char original[], char toFind[]);
void insertString(char original[], int start, int length, char toInsert[]);
int main(int argc, char *argv[]) {
//make the text buffer and zero it
char text[NUM_ROWS][ROW_LENTH];
for (int i = 0; i < NUM_ROWS; i++) {
text[i][0] = '0';
}
//check for file path arguments
if (argc == 2) {
printf("File argument detected. Reading file... ");
//read the file
if (readFile(argv[1], text)) {
printf("File read successfully ");
} else {
printf("File read unsuccessful ");
}
}
//continue asking for input until the user chooses to quit
char userInput = '0';
while(userInput != 'q') {
//print out the text buffer
printText(text);
//ask for and get input
printf("Enter q to quit, r to replace a line, i to insert a substring over another ");
userInput = getchar();
switch (userInput) {
//if they want to quit
case 'q':
printf("You have chosen to quit. Goodbye! ");
//save the text buffer back to the file
if (argc == 2) {
printf("Changes will now be saved to file ");
if (writeFile(argv[1], text)) {
printf("File written successfully ");
} else {
printf("Error writing file ");
}
}
break;
//if they want to replace an entire line
case 'r':
//get the line
replaceLine(text[getLine()]);
break;
case 'i':
//must have an empty statement because a variable cannot be
//declared as part of the same statement as a label
;
int lineNum = getLine();
//print that one line
printf("Line %c looks like: %s ", lineNum, text[lineNum]);
//get the substring to replace
char toReplace[ROW_LENTH];
printf("Please enter the subSring to replace in the line: ");
flushBuffer();
fgets(toReplace, ROW_LENTH, stdin);
removeTrailingHardReturn(toReplace);
//get the substring to replace with
char replaceWith[ROW_LENTH];
printf("Please enter the subSring to replace the old subString with: ");
fgets(replaceWith, ROW_LENTH, stdin);
removeTrailingHardReturn(replaceWith);
//do the replacement
if (replaceInString(text[lineNum], toReplace, replaceWith)) {
printf("Replacement successful! ");
} else {
printf("Replacement unsuccessful! ");
}
break;
default:
printf("Invalid input. Please try again ");
break;
}
}
return 0;
}
/*
This function overwrites one of the lines in the text
PARAMS:
line, a char array containing the line to overwrite
*/
void replaceLine(char line[]) {
flushBuffer();
printf("Please enter the text to replace the line with: ");
fgets(line, ROW_LENTH, stdin);
removeTrailingHardReturn(line);
}
/*
This function prints the all 5 lines for the user to see
PARAMS:
text, a 2D char array containing all 5 lines of the text
*/
void printText(char text[][ROW_LENTH]) {
//print all 5 lines
printf("The text currently looks like: ");
for (int i = 0; i < NUM_ROWS; i++) {
if (strlen(text[i]) == 0) {
printf("*LINE EMPTY* ");
} else {
printf("%s ", text[i]);
}
}
}
/*
This function reads lines of text from a file and puts them into the text array
PARAMS:
filePath, a string containing the path to the file with the data
text, a 2D char array containing all 5 lines of the text
*/
int readFile(char filePath[], char text[][ROW_LENTH]) {
//open the file
FILE* inFile = fopen(filePath, "r");
//check to see if the file exists
if (inFile != NULL) {
//read 5 lines or until end of file
for (int i = 0; i < 5 && !feof(inFile); i++) {
fscanf(inFile, "%s", text[i]);
removeTrailingHardReturn(text[i]);
}
//close file
fclose(inFile);
return 1;
} else {
//close file, return fail
fclose(inFile);
return 0;
}
}
/*
This function writes the user's text to a file
PARAMS:
filePath, a string containing the path to the file with the data
text, a 2D char array containing all 5 lines of the text
*/
int writeFile(char filePath[], char text[][ROW_LENTH]) {
//open the file
FILE* outFile = fopen(filePath, "w");
//check that it worked
if (outFile == NULL) {
return 0;
}else {
//write all 5 lines
for (int i = 0; i < 5; i++) {
fprintf(outFile, "%s ", text[i]);
}
//close and return
fclose(outFile);
return 1;
}
}
/*
This function removes the newline character from the end of a string
PARAMS:
line, a char array containing the line remove the hard return from
*/
void removeTrailingHardReturn(char line[]) {
//remove the new line at the end
if (line[strlen(line) - 1] == ' ') {
line[strlen(line) - 1] = '0';
} else {
//if there was no newline, then flush the buffer because it's still in there
flushBuffer();
}
}
/*
This function removes everything from the input stream buffer so that
there is no erratic input to my menus from truncated input,
also removes the newlines from the end of input
*/
void flushBuffer() {
char input = '0';
do {
input = getchar();
} while (input != ' ' && input != EOF);
}
/*
This finction gets an integer input from 1 to the number of rows.
RETURNS
An integer from 1-5 (inclusive)
*/
int getLine() {
int validLine = 0;
int lineNum = -1;
//loop until the user input is valid
while (!validLine){
//ask for and get 1 character of input
printf("Please enter a line number to replace (1-5) ");
flushBuffer();
lineNum = getchar();
//check that it is a number between 1 and the number of rows (inclusive)
if (lineNum >= '1' && lineNum <= NUM_ROWS + 49) {
//if it is, return
return (int) lineNum - 49;
} else {
printf("Invalid input. Please try again. ");
}
}
return -1;
}
/*
This function utilizes findsubstring and insertstring to overwrite a substring
in a string with another
PARAMS
original, a character array that has the string that is to be changed
subString, a character array that contains the substring in original to be replaced
replace, a character array to replace the subString in original with
RETURNS
1 if successful (substring was found and replaced), 0 otherwise
*/
int replaceInString(char original[], char substring[], char replace[]) {
//find the location of the substring
int location = findSubString(original, substring);
//check to see if the substring is in the original string
if (location == -1) {
return 0;
} else {
//insert the string an return depending on success
insertString(original, location, strlen(substring), replace);
return 1;
}
}
/*
This function finds the first occurance of a substring in a string
PARAMS:
original, a char array of the string to search for the substring
toFind, a char array with the substring to search for
RETURNS
the index of the first character in the substring, or -1 if the substring was not found
*/
int findSubString(char original[], char toFind[]) {
//loop through the string
for (int i = 0; i < strlen(original); i++) {
//if it matches the first character begin looping through the substring
if (original[i] == toFind[0]) {
short match = 1;
//check that the following characters match the substring
for (int j = 1; j < strlen(toFind); j++) {
if (original[i + j] != toFind[j]) {
match = 0;
break;
}
}
//if they all match, return the location
if (match) {
return i;
}
}
}
return -1;
}
/*
This function inserts a string into another, overwriting part of that string
PARAMS:
original, a char array of the string to be changed
start, the index at which to insert the first character of the substring ebing inserted
length, the length of the original to be overwritten
toInsert, the substring to insert into the original string
RETURNS
1 if successful, 0 if not successful
*/
void insertString(char original[], int start, int length, char toInsert[]) {
if (start < 0 || length < 0) {
printf("Invalid parameter, no changes made ");
return;
}
//create a copy of the original string
char originalCopy[ROW_LENTH];
strcpy(originalCopy, original);
//end the string where the inserting string will start
original[start] = '0';
//add the inserted string
strcat(original, toInsert);
//add the end of the original string back to the end of the new string
for (int i = start + length; i < strlen(originalCopy); i++) {
int len = strlen(original);
original[len] = originalCopy[i];
original[len + 1] = '0';
}
}

More Related Content

Similar to The Task For this assignment you will write a rudimentary text edi.pdf

META-INFMANIFEST.MFManifest-Version 1.0.classpath.docx
META-INFMANIFEST.MFManifest-Version 1.0.classpath.docxMETA-INFMANIFEST.MFManifest-Version 1.0.classpath.docx
META-INFMANIFEST.MFManifest-Version 1.0.classpath.docxandreecapon
 
Part 1)#include stdio.h #include stdlib.h #include pthrea.pdf
Part 1)#include stdio.h #include stdlib.h #include pthrea.pdfPart 1)#include stdio.h #include stdlib.h #include pthrea.pdf
Part 1)#include stdio.h #include stdlib.h #include pthrea.pdfmohammadirfan136964
 
Note Modified codecode#includeiostream #include stdio.h.pdf
Note Modified codecode#includeiostream #include stdio.h.pdfNote Modified codecode#includeiostream #include stdio.h.pdf
Note Modified codecode#includeiostream #include stdio.h.pdfsharnapiyush773
 
Diploma ii cfpc u-4 function, storage class and array and strings
Diploma ii  cfpc u-4 function, storage class and array and stringsDiploma ii  cfpc u-4 function, storage class and array and strings
Diploma ii cfpc u-4 function, storage class and array and stringsRai University
 
Current C++ code- parse-h -- This file contains the function prototype (1).pdf
Current C++ code- parse-h -- This file contains the function prototype (1).pdfCurrent C++ code- parse-h -- This file contains the function prototype (1).pdf
Current C++ code- parse-h -- This file contains the function prototype (1).pdfshyamsunder1211
 
Lecture 15_Strings and Dynamic Memory Allocation.pptx
Lecture 15_Strings and  Dynamic Memory Allocation.pptxLecture 15_Strings and  Dynamic Memory Allocation.pptx
Lecture 15_Strings and Dynamic Memory Allocation.pptxJawadTanvir
 
#ifndef MYLIST_H_ #define MYLIST_H_#includeiostream #include.docx
#ifndef MYLIST_H_ #define MYLIST_H_#includeiostream #include.docx#ifndef MYLIST_H_ #define MYLIST_H_#includeiostream #include.docx
#ifndef MYLIST_H_ #define MYLIST_H_#includeiostream #include.docxajoy21
 
helpInstructionsAdd the function max as an abstract function to .pdf
helpInstructionsAdd the function max as an abstract function to .pdfhelpInstructionsAdd the function max as an abstract function to .pdf
helpInstructionsAdd the function max as an abstract function to .pdfalmonardfans
 
Dti2143 chapter 5
Dti2143 chapter 5Dti2143 chapter 5
Dti2143 chapter 5alish sha
 
Write a program that converts an infix expression into an equivalent.pdf
Write a program that converts an infix expression into an equivalent.pdfWrite a program that converts an infix expression into an equivalent.pdf
Write a program that converts an infix expression into an equivalent.pdfmohdjakirfb
 
For this homework, you will write a program to create and manipulate.pdf
For this homework, you will write a program to create and manipulate.pdfFor this homework, you will write a program to create and manipulate.pdf
For this homework, you will write a program to create and manipulate.pdfherminaherman
 
Assignment c programming
Assignment c programmingAssignment c programming
Assignment c programmingIcaii Infotech
 
Unit 4
Unit 4Unit 4
Unit 4siddr
 
ObjectivesMore practice with recursion.Practice writing some tem.docx
ObjectivesMore practice with recursion.Practice writing some tem.docxObjectivesMore practice with recursion.Practice writing some tem.docx
ObjectivesMore practice with recursion.Practice writing some tem.docxvannagoforth
 
Given an expression string exp, write a java class ExpressionCheccke.pdf
Given an expression string exp, write a java class ExpressionCheccke.pdfGiven an expression string exp, write a java class ExpressionCheccke.pdf
Given an expression string exp, write a java class ExpressionCheccke.pdfinfo382133
 
Btech i pic u-4 function, storage class and array and strings
Btech i pic u-4 function, storage class and array and stringsBtech i pic u-4 function, storage class and array and strings
Btech i pic u-4 function, storage class and array and stringsRai University
 

Similar to The Task For this assignment you will write a rudimentary text edi.pdf (20)

easyPy-Basic.pdf
easyPy-Basic.pdfeasyPy-Basic.pdf
easyPy-Basic.pdf
 
META-INFMANIFEST.MFManifest-Version 1.0.classpath.docx
META-INFMANIFEST.MFManifest-Version 1.0.classpath.docxMETA-INFMANIFEST.MFManifest-Version 1.0.classpath.docx
META-INFMANIFEST.MFManifest-Version 1.0.classpath.docx
 
[ITP - Lecture 17] Strings in C/C++
[ITP - Lecture 17] Strings in C/C++[ITP - Lecture 17] Strings in C/C++
[ITP - Lecture 17] Strings in C/C++
 
Part 1)#include stdio.h #include stdlib.h #include pthrea.pdf
Part 1)#include stdio.h #include stdlib.h #include pthrea.pdfPart 1)#include stdio.h #include stdlib.h #include pthrea.pdf
Part 1)#include stdio.h #include stdlib.h #include pthrea.pdf
 
Note Modified codecode#includeiostream #include stdio.h.pdf
Note Modified codecode#includeiostream #include stdio.h.pdfNote Modified codecode#includeiostream #include stdio.h.pdf
Note Modified codecode#includeiostream #include stdio.h.pdf
 
Diploma ii cfpc u-4 function, storage class and array and strings
Diploma ii  cfpc u-4 function, storage class and array and stringsDiploma ii  cfpc u-4 function, storage class and array and strings
Diploma ii cfpc u-4 function, storage class and array and strings
 
Unitii string
Unitii stringUnitii string
Unitii string
 
Current C++ code- parse-h -- This file contains the function prototype (1).pdf
Current C++ code- parse-h -- This file contains the function prototype (1).pdfCurrent C++ code- parse-h -- This file contains the function prototype (1).pdf
Current C++ code- parse-h -- This file contains the function prototype (1).pdf
 
Lecture 15_Strings and Dynamic Memory Allocation.pptx
Lecture 15_Strings and  Dynamic Memory Allocation.pptxLecture 15_Strings and  Dynamic Memory Allocation.pptx
Lecture 15_Strings and Dynamic Memory Allocation.pptx
 
#ifndef MYLIST_H_ #define MYLIST_H_#includeiostream #include.docx
#ifndef MYLIST_H_ #define MYLIST_H_#includeiostream #include.docx#ifndef MYLIST_H_ #define MYLIST_H_#includeiostream #include.docx
#ifndef MYLIST_H_ #define MYLIST_H_#includeiostream #include.docx
 
helpInstructionsAdd the function max as an abstract function to .pdf
helpInstructionsAdd the function max as an abstract function to .pdfhelpInstructionsAdd the function max as an abstract function to .pdf
helpInstructionsAdd the function max as an abstract function to .pdf
 
Dti2143 chapter 5
Dti2143 chapter 5Dti2143 chapter 5
Dti2143 chapter 5
 
Write a program that converts an infix expression into an equivalent.pdf
Write a program that converts an infix expression into an equivalent.pdfWrite a program that converts an infix expression into an equivalent.pdf
Write a program that converts an infix expression into an equivalent.pdf
 
For this homework, you will write a program to create and manipulate.pdf
For this homework, you will write a program to create and manipulate.pdfFor this homework, you will write a program to create and manipulate.pdf
For this homework, you will write a program to create and manipulate.pdf
 
Assignment c programming
Assignment c programmingAssignment c programming
Assignment c programming
 
Unit 4
Unit 4Unit 4
Unit 4
 
M C6java7
M C6java7M C6java7
M C6java7
 
ObjectivesMore practice with recursion.Practice writing some tem.docx
ObjectivesMore practice with recursion.Practice writing some tem.docxObjectivesMore practice with recursion.Practice writing some tem.docx
ObjectivesMore practice with recursion.Practice writing some tem.docx
 
Given an expression string exp, write a java class ExpressionCheccke.pdf
Given an expression string exp, write a java class ExpressionCheccke.pdfGiven an expression string exp, write a java class ExpressionCheccke.pdf
Given an expression string exp, write a java class ExpressionCheccke.pdf
 
Btech i pic u-4 function, storage class and array and strings
Btech i pic u-4 function, storage class and array and stringsBtech i pic u-4 function, storage class and array and strings
Btech i pic u-4 function, storage class and array and strings
 

More from info785431

Carbon dioxide (CO_2) is a non-polar molecule. Is this consistent wit.pdf
Carbon dioxide (CO_2) is a non-polar molecule. Is this consistent wit.pdfCarbon dioxide (CO_2) is a non-polar molecule. Is this consistent wit.pdf
Carbon dioxide (CO_2) is a non-polar molecule. Is this consistent wit.pdfinfo785431
 
Compare and contrast the messages about science and integrity in Fra.pdf
Compare and contrast the messages about science and integrity in Fra.pdfCompare and contrast the messages about science and integrity in Fra.pdf
Compare and contrast the messages about science and integrity in Fra.pdfinfo785431
 
Briely, what was Darwins explanation for the appearance of design.pdf
Briely, what was Darwins explanation for the appearance of design.pdfBriely, what was Darwins explanation for the appearance of design.pdf
Briely, what was Darwins explanation for the appearance of design.pdfinfo785431
 
A router receives a message addressed 172.16.15.75. The relevant rou.pdf
A router receives a message addressed 172.16.15.75. The relevant rou.pdfA router receives a message addressed 172.16.15.75. The relevant rou.pdf
A router receives a message addressed 172.16.15.75. The relevant rou.pdfinfo785431
 
A study of sandflies in Panama classified flies caught in light traps.pdf
A study of sandflies in Panama classified flies caught in light traps.pdfA study of sandflies in Panama classified flies caught in light traps.pdf
A study of sandflies in Panama classified flies caught in light traps.pdfinfo785431
 
___Tissue found in the brain, spinal cord, and peripheral nerves. The.pdf
___Tissue found in the brain, spinal cord, and peripheral nerves. The.pdf___Tissue found in the brain, spinal cord, and peripheral nerves. The.pdf
___Tissue found in the brain, spinal cord, and peripheral nerves. The.pdfinfo785431
 
You have been exposed to each of the 8 microbes below. One of them h.pdf
You have been exposed to each of the 8 microbes below. One of them h.pdfYou have been exposed to each of the 8 microbes below. One of them h.pdf
You have been exposed to each of the 8 microbes below. One of them h.pdfinfo785431
 
Write a snippet of C code that will enable the ADC to continuously r.pdf
Write a snippet of C code that will enable the ADC to continuously r.pdfWrite a snippet of C code that will enable the ADC to continuously r.pdf
Write a snippet of C code that will enable the ADC to continuously r.pdfinfo785431
 
Write a JAVA LinkedListRec class that has the following methods siz.pdf
Write a JAVA LinkedListRec class that has the following methods siz.pdfWrite a JAVA LinkedListRec class that has the following methods siz.pdf
Write a JAVA LinkedListRec class that has the following methods siz.pdfinfo785431
 
Write a BFS algorithm using only arrays and no other data structure..pdf
Write a BFS algorithm using only arrays and no other data structure..pdfWrite a BFS algorithm using only arrays and no other data structure..pdf
Write a BFS algorithm using only arrays and no other data structure..pdfinfo785431
 
Why has one prominent textbook author described IO management as the.pdf
Why has one prominent textbook author described IO management as the.pdfWhy has one prominent textbook author described IO management as the.pdf
Why has one prominent textbook author described IO management as the.pdfinfo785431
 
which is true of the data shown in the histogram Which is true of th.pdf
which is true of the data shown in the histogram Which is true of th.pdfwhich is true of the data shown in the histogram Which is true of th.pdf
which is true of the data shown in the histogram Which is true of th.pdfinfo785431
 
What is the value of studying humanities in a business or technical .pdf
What is the value of studying humanities in a business or technical .pdfWhat is the value of studying humanities in a business or technical .pdf
What is the value of studying humanities in a business or technical .pdfinfo785431
 
What are the two components of dynamic pressureVelocity and densi.pdf
What are the two components of dynamic pressureVelocity and densi.pdfWhat are the two components of dynamic pressureVelocity and densi.pdf
What are the two components of dynamic pressureVelocity and densi.pdfinfo785431
 
USING JAVAImplement the quicksort optimization median-of-three, i.pdf
USING JAVAImplement the quicksort optimization median-of-three, i.pdfUSING JAVAImplement the quicksort optimization median-of-three, i.pdf
USING JAVAImplement the quicksort optimization median-of-three, i.pdfinfo785431
 
There are 40 students in our class. How many ways they can be lined .pdf
There are 40 students in our class. How many ways they can be lined .pdfThere are 40 students in our class. How many ways they can be lined .pdf
There are 40 students in our class. How many ways they can be lined .pdfinfo785431
 
The SIP handles what functionsA.) establishes a call through the .pdf
The SIP handles what functionsA.) establishes a call through the .pdfThe SIP handles what functionsA.) establishes a call through the .pdf
The SIP handles what functionsA.) establishes a call through the .pdfinfo785431
 
The NBA decides to look into the use of meldonium in the league foll.pdf
The NBA decides to look into the use of meldonium in the league foll.pdfThe NBA decides to look into the use of meldonium in the league foll.pdf
The NBA decides to look into the use of meldonium in the league foll.pdfinfo785431
 
The organelle that serves as the digestive system in the cell is the .pdf
The organelle that serves as the digestive system in the cell is the .pdfThe organelle that serves as the digestive system in the cell is the .pdf
The organelle that serves as the digestive system in the cell is the .pdfinfo785431
 
The major type of interactive forces between molecules of NH_3 are .pdf
The major type of interactive forces between molecules of NH_3 are  .pdfThe major type of interactive forces between molecules of NH_3 are  .pdf
The major type of interactive forces between molecules of NH_3 are .pdfinfo785431
 

More from info785431 (20)

Carbon dioxide (CO_2) is a non-polar molecule. Is this consistent wit.pdf
Carbon dioxide (CO_2) is a non-polar molecule. Is this consistent wit.pdfCarbon dioxide (CO_2) is a non-polar molecule. Is this consistent wit.pdf
Carbon dioxide (CO_2) is a non-polar molecule. Is this consistent wit.pdf
 
Compare and contrast the messages about science and integrity in Fra.pdf
Compare and contrast the messages about science and integrity in Fra.pdfCompare and contrast the messages about science and integrity in Fra.pdf
Compare and contrast the messages about science and integrity in Fra.pdf
 
Briely, what was Darwins explanation for the appearance of design.pdf
Briely, what was Darwins explanation for the appearance of design.pdfBriely, what was Darwins explanation for the appearance of design.pdf
Briely, what was Darwins explanation for the appearance of design.pdf
 
A router receives a message addressed 172.16.15.75. The relevant rou.pdf
A router receives a message addressed 172.16.15.75. The relevant rou.pdfA router receives a message addressed 172.16.15.75. The relevant rou.pdf
A router receives a message addressed 172.16.15.75. The relevant rou.pdf
 
A study of sandflies in Panama classified flies caught in light traps.pdf
A study of sandflies in Panama classified flies caught in light traps.pdfA study of sandflies in Panama classified flies caught in light traps.pdf
A study of sandflies in Panama classified flies caught in light traps.pdf
 
___Tissue found in the brain, spinal cord, and peripheral nerves. The.pdf
___Tissue found in the brain, spinal cord, and peripheral nerves. The.pdf___Tissue found in the brain, spinal cord, and peripheral nerves. The.pdf
___Tissue found in the brain, spinal cord, and peripheral nerves. The.pdf
 
You have been exposed to each of the 8 microbes below. One of them h.pdf
You have been exposed to each of the 8 microbes below. One of them h.pdfYou have been exposed to each of the 8 microbes below. One of them h.pdf
You have been exposed to each of the 8 microbes below. One of them h.pdf
 
Write a snippet of C code that will enable the ADC to continuously r.pdf
Write a snippet of C code that will enable the ADC to continuously r.pdfWrite a snippet of C code that will enable the ADC to continuously r.pdf
Write a snippet of C code that will enable the ADC to continuously r.pdf
 
Write a JAVA LinkedListRec class that has the following methods siz.pdf
Write a JAVA LinkedListRec class that has the following methods siz.pdfWrite a JAVA LinkedListRec class that has the following methods siz.pdf
Write a JAVA LinkedListRec class that has the following methods siz.pdf
 
Write a BFS algorithm using only arrays and no other data structure..pdf
Write a BFS algorithm using only arrays and no other data structure..pdfWrite a BFS algorithm using only arrays and no other data structure..pdf
Write a BFS algorithm using only arrays and no other data structure..pdf
 
Why has one prominent textbook author described IO management as the.pdf
Why has one prominent textbook author described IO management as the.pdfWhy has one prominent textbook author described IO management as the.pdf
Why has one prominent textbook author described IO management as the.pdf
 
which is true of the data shown in the histogram Which is true of th.pdf
which is true of the data shown in the histogram Which is true of th.pdfwhich is true of the data shown in the histogram Which is true of th.pdf
which is true of the data shown in the histogram Which is true of th.pdf
 
What is the value of studying humanities in a business or technical .pdf
What is the value of studying humanities in a business or technical .pdfWhat is the value of studying humanities in a business or technical .pdf
What is the value of studying humanities in a business or technical .pdf
 
What are the two components of dynamic pressureVelocity and densi.pdf
What are the two components of dynamic pressureVelocity and densi.pdfWhat are the two components of dynamic pressureVelocity and densi.pdf
What are the two components of dynamic pressureVelocity and densi.pdf
 
USING JAVAImplement the quicksort optimization median-of-three, i.pdf
USING JAVAImplement the quicksort optimization median-of-three, i.pdfUSING JAVAImplement the quicksort optimization median-of-three, i.pdf
USING JAVAImplement the quicksort optimization median-of-three, i.pdf
 
There are 40 students in our class. How many ways they can be lined .pdf
There are 40 students in our class. How many ways they can be lined .pdfThere are 40 students in our class. How many ways they can be lined .pdf
There are 40 students in our class. How many ways they can be lined .pdf
 
The SIP handles what functionsA.) establishes a call through the .pdf
The SIP handles what functionsA.) establishes a call through the .pdfThe SIP handles what functionsA.) establishes a call through the .pdf
The SIP handles what functionsA.) establishes a call through the .pdf
 
The NBA decides to look into the use of meldonium in the league foll.pdf
The NBA decides to look into the use of meldonium in the league foll.pdfThe NBA decides to look into the use of meldonium in the league foll.pdf
The NBA decides to look into the use of meldonium in the league foll.pdf
 
The organelle that serves as the digestive system in the cell is the .pdf
The organelle that serves as the digestive system in the cell is the .pdfThe organelle that serves as the digestive system in the cell is the .pdf
The organelle that serves as the digestive system in the cell is the .pdf
 
The major type of interactive forces between molecules of NH_3 are .pdf
The major type of interactive forces between molecules of NH_3 are  .pdfThe major type of interactive forces between molecules of NH_3 are  .pdf
The major type of interactive forces between molecules of NH_3 are .pdf
 

Recently uploaded

How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSCeline George
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...pradhanghanshyam7136
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17Celine George
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin ClassesCeline George
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxDyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxcallscotland1987
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxnegromaestrong
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfSherif Taha
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseAnaAcapella
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 

Recently uploaded (20)

How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxDyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptx
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 

The Task For this assignment you will write a rudimentary text edi.pdf

  • 1. The Task For this assignment you will write a rudimentary text editor that allows the user to edit 5 lines of text, where each line is no longer than 80 characters. The editor should allow the user to continue editing as long as desired and should print the current state of the edit buffer after each edit. The editor is a 'line editor' in that the user must edit one line at a time. The user can specify which line should be edited by choosing a line number from a menu. The only two editing operations possible are to replace an entire line with a new line, or to replace a substring in the line with a new substring. Musts The program should not accept incorrect menu choices from the user. If the user creates a string that is longer than 80 characters the string should be truncated to fit the 80 character limit. The program should simply make no changes if the user tries to replace a substring that does not exist in the string. Your program must use functions. Some functions are required, but you may make other functions as you see fit. You may not change the name, return type, or the parameter list types for required functions. Required Function One int replaceInString(char[] original, char[] substring, char[] replace); This function causes the original string to be modified such that the first occurrence of substring is removed from the original string and the contents of replace are inserted in its place. replaceInString calls findSubString and insertString. The function returns 0 if the operation fails and 1 if the operation is successful. Required Function Two: int findSubString(char[] original, char[] toFind); This function finds the first occurrence of toFind in original and returns an integer representing the index of the first element of the toFind substring in original. For example if toFind was 'cat' and original was 'thundercat' the function would return 7 since the begining of 'cat' in 'thundercat' is position 7. If the function does not find a substring it should return -1 note: do not use existing substring functions such as strstr as a solution for this function. Solve the algorithm yourself. You may use basic string functions such as strlen and strcat. Required Function Three: int insertString(char[] original, int start, int length, char[] toInsert); This function replaces the contents of original with the following sequence of characters:
  • 2. the characters from original up to position start- the characters from toInsert the characters from original starting at the character immediately after length. Solution #include #include #define ROW_LENTH 81 #define NUM_ROWS 5 void replaceLine(char line[]); void printText(char text[][ROW_LENTH]); int readFile(char filePath[], char text[][ROW_LENTH]); int writeFile(char filePath[], char text[][ROW_LENTH]); void removeTrailingHardReturn(char line[]); void flushBuffer(); int getLine(); int replaceInString(char original[], char substring[], char replace[]); int findSubString(char original[], char toFind[]); void insertString(char original[], int start, int length, char toInsert[]); int main(int argc, char *argv[]) { //make the text buffer and zero it char text[NUM_ROWS][ROW_LENTH]; for (int i = 0; i < NUM_ROWS; i++) { text[i][0] = '0'; } //check for file path arguments if (argc == 2) { printf("File argument detected. Reading file... "); //read the file if (readFile(argv[1], text)) { printf("File read successfully "); } else {
  • 3. printf("File read unsuccessful "); } } //continue asking for input until the user chooses to quit char userInput = '0'; while(userInput != 'q') { //print out the text buffer printText(text); //ask for and get input printf("Enter q to quit, r to replace a line, i to insert a substring over another "); userInput = getchar(); switch (userInput) { //if they want to quit case 'q': printf("You have chosen to quit. Goodbye! "); //save the text buffer back to the file if (argc == 2) { printf("Changes will now be saved to file "); if (writeFile(argv[1], text)) { printf("File written successfully "); } else { printf("Error writing file "); } } break; //if they want to replace an entire line case 'r': //get the line replaceLine(text[getLine()]); break; case 'i': //must have an empty statement because a variable cannot be //declared as part of the same statement as a label ; int lineNum = getLine();
  • 4. //print that one line printf("Line %c looks like: %s ", lineNum, text[lineNum]); //get the substring to replace char toReplace[ROW_LENTH]; printf("Please enter the subSring to replace in the line: "); flushBuffer(); fgets(toReplace, ROW_LENTH, stdin); removeTrailingHardReturn(toReplace); //get the substring to replace with char replaceWith[ROW_LENTH]; printf("Please enter the subSring to replace the old subString with: "); fgets(replaceWith, ROW_LENTH, stdin); removeTrailingHardReturn(replaceWith); //do the replacement if (replaceInString(text[lineNum], toReplace, replaceWith)) { printf("Replacement successful! "); } else { printf("Replacement unsuccessful! "); } break; default: printf("Invalid input. Please try again "); break; } } return 0; } /* This function overwrites one of the lines in the text PARAMS: line, a char array containing the line to overwrite */ void replaceLine(char line[]) { flushBuffer(); printf("Please enter the text to replace the line with: ");
  • 5. fgets(line, ROW_LENTH, stdin); removeTrailingHardReturn(line); } /* This function prints the all 5 lines for the user to see PARAMS: text, a 2D char array containing all 5 lines of the text */ void printText(char text[][ROW_LENTH]) { //print all 5 lines printf("The text currently looks like: "); for (int i = 0; i < NUM_ROWS; i++) { if (strlen(text[i]) == 0) { printf("*LINE EMPTY* "); } else { printf("%s ", text[i]); } } } /* This function reads lines of text from a file and puts them into the text array PARAMS: filePath, a string containing the path to the file with the data text, a 2D char array containing all 5 lines of the text */ int readFile(char filePath[], char text[][ROW_LENTH]) { //open the file FILE* inFile = fopen(filePath, "r"); //check to see if the file exists if (inFile != NULL) { //read 5 lines or until end of file for (int i = 0; i < 5 && !feof(inFile); i++) { fscanf(inFile, "%s", text[i]); removeTrailingHardReturn(text[i]); } //close file
  • 6. fclose(inFile); return 1; } else { //close file, return fail fclose(inFile); return 0; } } /* This function writes the user's text to a file PARAMS: filePath, a string containing the path to the file with the data text, a 2D char array containing all 5 lines of the text */ int writeFile(char filePath[], char text[][ROW_LENTH]) { //open the file FILE* outFile = fopen(filePath, "w"); //check that it worked if (outFile == NULL) { return 0; }else { //write all 5 lines for (int i = 0; i < 5; i++) { fprintf(outFile, "%s ", text[i]); } //close and return fclose(outFile); return 1; } } /* This function removes the newline character from the end of a string PARAMS: line, a char array containing the line remove the hard return from */ void removeTrailingHardReturn(char line[]) {
  • 7. //remove the new line at the end if (line[strlen(line) - 1] == ' ') { line[strlen(line) - 1] = '0'; } else { //if there was no newline, then flush the buffer because it's still in there flushBuffer(); } } /* This function removes everything from the input stream buffer so that there is no erratic input to my menus from truncated input, also removes the newlines from the end of input */ void flushBuffer() { char input = '0'; do { input = getchar(); } while (input != ' ' && input != EOF); } /* This finction gets an integer input from 1 to the number of rows. RETURNS An integer from 1-5 (inclusive) */ int getLine() { int validLine = 0; int lineNum = -1; //loop until the user input is valid while (!validLine){ //ask for and get 1 character of input printf("Please enter a line number to replace (1-5) "); flushBuffer(); lineNum = getchar(); //check that it is a number between 1 and the number of rows (inclusive) if (lineNum >= '1' && lineNum <= NUM_ROWS + 49) { //if it is, return
  • 8. return (int) lineNum - 49; } else { printf("Invalid input. Please try again. "); } } return -1; } /* This function utilizes findsubstring and insertstring to overwrite a substring in a string with another PARAMS original, a character array that has the string that is to be changed subString, a character array that contains the substring in original to be replaced replace, a character array to replace the subString in original with RETURNS 1 if successful (substring was found and replaced), 0 otherwise */ int replaceInString(char original[], char substring[], char replace[]) { //find the location of the substring int location = findSubString(original, substring); //check to see if the substring is in the original string if (location == -1) { return 0; } else { //insert the string an return depending on success insertString(original, location, strlen(substring), replace); return 1; } } /* This function finds the first occurance of a substring in a string PARAMS: original, a char array of the string to search for the substring toFind, a char array with the substring to search for RETURNS the index of the first character in the substring, or -1 if the substring was not found
  • 9. */ int findSubString(char original[], char toFind[]) { //loop through the string for (int i = 0; i < strlen(original); i++) { //if it matches the first character begin looping through the substring if (original[i] == toFind[0]) { short match = 1; //check that the following characters match the substring for (int j = 1; j < strlen(toFind); j++) { if (original[i + j] != toFind[j]) { match = 0; break; } } //if they all match, return the location if (match) { return i; } } } return -1; } /* This function inserts a string into another, overwriting part of that string PARAMS: original, a char array of the string to be changed start, the index at which to insert the first character of the substring ebing inserted length, the length of the original to be overwritten toInsert, the substring to insert into the original string RETURNS 1 if successful, 0 if not successful */ void insertString(char original[], int start, int length, char toInsert[]) { if (start < 0 || length < 0) { printf("Invalid parameter, no changes made "); return;
  • 10. } //create a copy of the original string char originalCopy[ROW_LENTH]; strcpy(originalCopy, original); //end the string where the inserting string will start original[start] = '0'; //add the inserted string strcat(original, toInsert); //add the end of the original string back to the end of the new string for (int i = start + length; i < strlen(originalCopy); i++) { int len = strlen(original); original[len] = originalCopy[i]; original[len + 1] = '0'; } }