added weekly exercises of isp-ws25

This commit is contained in:
2026-04-13 19:02:19 +02:00
parent c51e836ed9
commit 00fdd31a18
28 changed files with 1835 additions and 0 deletions

View File

@@ -0,0 +1,104 @@
/*
In this task, you should get familiar with file I/O operations in C
by writing a program that reads the text file sentences.txt and counts
both the number of words and the number of characters (excluding line breaks).
Tasks:
- Open "sentences.txt" using fopen.
- if open fails (i.e., fopen returns NULL):
- Print the error message "Could not open file\n"
- return 1
- User Input: line number that should be analyzed
- Line numbers are 1-based (if user enters "1", analyze first line)
- Read file (e.g., using fgetc)
- analyze correct line
- Count words separated by whitespace.
- Count characters (excluding line break).
- Close file properly after processing.
- Print word count and character count according to example output below.
- If entered line number is not in range line numbers of file:
- print "Could not analyze line\n".
Examples:
Line number to analyze: 5
Word Count: 4
Character Count: 22
Line number to analyze: 1
Word Count: 12
Character Count: 80
Line number to analyze: 22
Word Count: 14
Character Count: 76
*/
#include <ctype.h>
#include <stdio.h>
#include <string.h>
int main(void)
{
printf("Line number to analyze: ");
int line_number;
scanf("%d", &line_number);
if (line_number < 1)
{
printf("Could not analyze line\n");
return 0;
}
FILE *file = fopen("sentences.txt", "r");
if (file == NULL)
{
printf("Could not open file\n");
return 1;
}
int current_line = 1;
int word_count = 0;
int char_count = 0;
int character = 0;
int saw_char = 0;
while ((character = fgetc(file)) != EOF)
{
if(current_line != line_number && character != '\n') continue;
if (character == '\n')
{
if (current_line == line_number) break;
current_line++;
continue;
}
if (current_line == line_number)
{
if (character != '\n') char_count++;
//It is rare to meet a Lannister who shares my enthusiasm for dead Lannisters.
if (isspace(character))
{
saw_char = 0;
}
else if (isgraph(character) && !saw_char)
{
word_count++;
saw_char = 1;
continue;
}
}
}
if (current_line < line_number)
{
printf("Could not analyze line\n");
}
else
{
printf("Word Count: %d\n", word_count);
printf("Character Count: %d\n", char_count);
}
fclose(file);
return 0;
}