Count Words
Diese Einsteigerübung trainiert grundlegende Syntax und Problemlösung anhand von Count Words.
Was ist Count Words?
Diese Einsteigerübung trainiert grundlegende Syntax und Problemlösung anhand von Count Words.
Löse Count Words mit ausführbarem Code in C und C++.
Wichtige Punkte
- Aktiviere Compiler-Warnungen und behebe sie vollständig.
- Kenne Typ und Lebensdauer jedes Werts.
- Prüfe Eingaben und Array-Grenzen explizit.
Codebeispiele in C und C++
main.c
#include <ctype.h>
#include <stdio.h>
int main(void) {
const char *text = "C and C++ examples"; int words = 0, inside = 0;
// Count transitions from whitespace into a word.
for (; *text; ++text) { if (isspace((unsigned char)*text)) inside = 0; else if (!inside) { ++words; inside = 1; } }
printf("words=%d\n", words);
}
words=4
main.cpp
#include <iostream>
#include <sstream>
#include <string>
int main() {
std::istringstream input("C and C++ examples"); std::string word; int words = 0;
// Formatted extraction skips whitespace and returns one word.
while (input >> word) ++words;
std::cout << "words=" << words << '\n';
}
words=4
Vergleich zwischen C und C++
Vergleiche die C- und C++-Implementierung, ändere die Eingaben und teste zusätzliche Randfälle.
C
C stellt kleine prozedurale APIs und Repräsentationsdetails offen dar.
C++
C++ behält das Low-Level-Modell und ergänzt sicherere Bibliothekstypen.
Übungsaufgaben
Führe beide Versionen aus und untersuche die unterschiedlichen Garantien.
- Füge ungültige und Grenzwerte hinzu.
- Kompiliere mit -Wall -Wextra -Wpedantic.
- Teile Deklaration und Implementierung auf.