Challenge
Swap the numbers surrounding the words in sentences.
Specifications
- The first argument is a path to a file.
- The file contains multiple lines.
- Each line is a test case represented by a sentence.
- Each sentence begins and ends with a number.
- Print out the sentence obtained by swapping the numbers surrounding each word.
Constraints
- The suffix and the prefix of each word may be equal.
- Sentences are from 1 to 17 words long.
- The number of test cases is 40.
- All characters are ASCII.
- The numbers are single digit positive intgers 0-9.
Sample Input
4Always0 5look8 4on9 7the2 4bright8 9side7 3of8 5life5
5Nobody5 7expects3 5the4 6Spanish4 9inquisition0
Sample Output
0Always4 8look5 9on4 2the7 8bright4 7side9 8of3 5life5
5Nobody5 3expects7 4the5 4Spanish6 0inquisition9
My solution
#include <stdio.h>
#include <ctype.h>
#define LINE_BUFFER 256
int fileExists(char *filename) {
FILE *file = fopen(filename, "r");
if (file != NULL) {
fclose(file);
}
return file != NULL;
}
void swapNumbers(char line[LINE_BUFFER]) {
int temp = 0;
int position = 0;
int swapped = 0;
for (int i = 0; i < LINE_BUFFER; i++) {
if (isdigit(line[i])) {
if (!swapped) {
position = i;
temp = line[i];
swapped = 1;
} else {
line[position] = line[i];
line[i] = temp;
swapped = 0;
}
}
}
}
int main(int argc, char *args[]) {
if (argc < 2) {
puts("File path not provided.");
return 1;
}
if (argc > 2) {
puts("Excessive arguments, only the first will be considered.");
}
if (!fileExists(args[1])) {
puts("Could not access file / file not found.");
return 1;
}
FILE *file = fopen(args[1], "r");
char line[LINE_BUFFER];
while (fgets(line, LINE_BUFFER, file)) {
swapNumbers(line);
printf("%s", line);
}
fclose(file);
}
fclose(file); } return file != NULL;uses the pointer valuefileafter thefclose(). I suspect this is generally OK, but smells of potential UB: using a pointer after it is no longer valid. \$\endgroup\$