Anfänger bis C++ und hier ProgrammierungCount Worte programmieren ganze Datei als ein Wort zu lesen
Ich möchte ein Programm schreiben, das die Anzahl der Wörter in einer Datei zählt. Ich teste es mit nur einer Datei, aber es sollte für andere Dateien mit unterschiedlicher Formatierung funktionieren, dh. mehrere Leerzeichen. (Ich gehe davon aus, dass es keine Probleme mit dem Öffnen der Datei etc jetzt)
ist hier mein Code:
#include <iostream> // these are the only imports I can use
#include <fstream>
#include <string>
using namespace std;
ifstream fin("story.txt"); // open the file called filename
void skip_space(char c) {
cout << "skip_space()\n";
while (c == ' ' || c == '\n' || c == '\t') { // as long as char is space
c = fin.get(); // get next character from file
if (fin.eof()) { // if eof is raised
return;
}
} // while
return;
}
void skip_char(char c) {
cout << "skip_char()\n";
while (c != ' ' || c != '\n' || c != '\t') { // as long as char is not space
c = fin.get(); // get next character from file
if (fin.eof()) { // if eof is raised
return;
}
}
return;
}
void num_words() {
cout << "num_words()\n";
int word_count = 0;
char c = fin.get(); // get first character of file
while (!fin.eof()) { // while not end of file
if (c == ' ' || c == '\n' || c == '\t') {
skip_space(c); // loops until an nonblank character is reached
} else { // if not a blank
word_count++; // increment count
skip_char(c); // loops until a space is reached
}
}
cout << "story.txt" << " has " << word_count << " words\n";
// prints a message to cout indicating the number of words in filename.
// A word is defined as the string that an input stream (such as cin) returns when reading a string value.
}
int main() {
num_words();
}
Hier sind die Inhalte der Datei:
One day
a green
a frog ate a
princess.
Als ich Führen Sie den Code der Ausgabe ist
Das Problem ist die Word_count ist 1 statt 9. Ich bin sehr verwirrt Im Algemeinen. Jede Hilfe wäre willkommen!
'(c! = '' || c! = '\ N' || c! = '\ T')' sollte sei '(c! = '' && c! = '\ n' && c! = '\ t')' –
Drei ist nicht vier. Vier ist nicht drei. Jede andere Zahl ist nicht drei und nicht vier. Also ist jede Zahl nicht drei oder nicht vier. –
Oohhh wie habe ich das nicht gesehen, danke! – Salvatross