Amount of words in file
Sep 20, 2019 at 2:15pm UTC
I want to find amount of words in my text file. But if on the end of the line is [space] my program stop work correct. How to stay away of this problem. Sorry for question, my first days in C++.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;
int main() {
fstream inputFile;
string Path;
cout << "Write path (like C:\\C++\\demofile.txt)\n" ;
getline(cin, Path);
inputFile.open(Path, ios::in);
string str, str2 = "" ;
int k = 0, Aw = 0;
if (inputFile.is_open()) {
while (getline(inputFile, str)) {
for (char c : str) {
if (c == ' ' ) {
++k;
}
else k = 0;
if (k <= 1) {
cout << c;
str2 += c;
}
}
++Aw;
str2 += "\n" ;
cout << "\n" ;
}
}
inputFile.close();
fstream outputFile;
outputFile.open(Path, ios::out);
for (char c : str2) {
if (c == ' ' ) ++Aw;
outputFile << c;
}
cout << Aw;
cin.get();
}
Last edited on Sep 20, 2019 at 2:19pm UTC
Sep 20, 2019 at 2:31pm UTC
If I may, I would just say scrap what you have and just use cin's >> operator, which already delimits the file by whitespace for you.
For example, this program will print every word (separated by whitespace):
file:
hello world
this is a text file, with words!
Includes punctuation....
program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include <iostream>
#include <string>
#include <fstream>
int main()
{
using namespace std;
ifstream fin("foo.txt" );
string word;
while (fin >> word)
{
std::cout << word << '\n' ;
}
}
output:
hello
world
this
is
a
text
file,
with
words!
Includes
punctuation....
______________________________________
But if on the end of the line is [space] my program stop work correct.
Describe exactly what you mean when you say the program is not correct
Last edited on Sep 20, 2019 at 2:33pm UTC
Topic archived. No new replies allowed.