Hey guys
So I'm trying to write a program that behaves as follows:
1. Define a word as any sequence of characters delimited by whitespace.
2. If the first character of a word were to be printed beyond the
first 72 columns, then delete the trailing whitespace characters of
x2, append '\n' to the end of x2, and then continue by appending that
word and the following characters to x2.
3. The C character '\n' represents a newline. After the newline,
consider the next character as appearing in the first column.
Continue to copy from x1 to x2, while keeping track of the current
column. When we go beyond the first 72 columns, then again execute
rule 2 above.
This is what I've been able to come up with:
Code:
#include <stdio.h>
main()
{
char x1[500] = "The quick brown fox jumped over the lazy dog. Now is"
" the time for all good men to come to the aid of their"
" country. We need another good and long sentence"
" to fill out this paragraph. By making this paragraph"
" longer, we will have a chance to insert lots of"
" newline characters.";
char x2[500], tmpArr[500];
int i, colCount, counter, curWordLength, atStartWord, offset, wasSpace, numSpacesToBeCleared;
colCount = i =counter = curWordLength = offset = wasSpace = numSpacesToBeCleared = 0;
atStartWord = 1;
/* While we are not on the last char.. */
while (x1[counter] != '\0'){
/* Check if a new word is starting */
if (wasSpace == 1){
if (x1[counter] != ' ' && x1[counter] != '\t'){
atStartWord = 1;
wasSpace = 0;
}
}
if(atStartWord == 1){
curWordLength = getWordLength(x1[500], colCount);
/* Word goes over 72, wrap it over HERE */
if(colCount + curWordLength >= 72){
/* Here we need to clear all the spaces at the end of the current line */
numSpacesToBeCleared = numBlankSpacesToKill(x2, counter);
while (i <= counter-numSpacesToBeCleared){
tmpArr[i] = x2[i];
i++;
}
x2[500] = tmpArr[500];
counter -= numSpacesToBeCleared;
offset += numSpacesToBeCleared;
x2[counter+offset] = '\n';
colCount = 0;
}
/* Else start copying it */
else{
x2[counter+offset] = x1[counter];
}
atStartWord = 0;
}
else{
x2[counter+offset] = x1[counter];
/* If this character is a space or a tab, set wasSpace to true */
if(x1[counter] == ' ' || x1[counter] == '\t'){
wasSpace = 1;
}
}
counter++;
}
printf("%d", x2);
}
/* Helper method
To determine the length of a word from a given starting point*/
int getWordLength(char arr[500], int start)
{
int counter, wordLength;
counter = wordLength = 0;
while (arr[start] != ' ' && arr[start] != '\t'){
wordLength = wordLength + 1;
start = start + 1;
}
return wordLength;
}
/* Helper method
To remove all the white spaces from the end of an array */
int numBlankSpacesToKill(char arr[500], int start){
int numWhiteSpaces;
numWhiteSpaces = 0;
while (arr[start] == ' ' || arr[start] == '\t'){
start--;
numWhiteSpaces++;
}
return numWhiteSpaces;
}
Running this on unix, I'm hitting a 'Segmentation fault' and having written this in only notepad and emacs/gcc these generic errors are driving me nuts..
Any ideas?