Program can't find which is the longest

This program detects which sentence is the longest in a notepad. It also gives the word count of the sentence.
This program worked when i first tried with just a few sentences.

But when i try with the sentences below and complicate it a bit more it does not work(starts giving wrong sentences/word count)

This sentence is long
This sentence is long too
Malow Mat Bow Fat Rat Cat
King queen fween is the best kind of sween.
All dead rising for the bed red.
Do you like to eat stuff.

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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#include <iostream>
#include <vector>
#include <fstream>
#include <string>
using namespace std;

vector<string>vec;
vector<int>words;


void input(){


ifstream file("C:\\Wordcount.txt"); //Sentences go inside the notepad 

if(file.is_open()){


while(file.good()){


string line;
getline(file,line);
vec.push_back(line);
}
int space=1;
int size=vec[0].size();
for(int a=0; a<vec.size();a++){
for(int b=0; b<size;b++){
if (vec[a][b]==' '){
space++;
}
}
words.push_back(space);
space=1;
}
for(int a=0; a<vec.size(); a++) {
for(int b=0; b<vec.size(); b++) {
if (words[a]>words[b]) {
swap(vec[a],vec[b]);
swap(words[a],words[b]);
}

}

}

}




}

void output(){

cout<<"Number of words are: "<<words[0]<<endl;
cout<<endl;
cout<<"The sentence is: "<<vec[0]<<endl;
cout<<endl;



}


void swap(int &a, int &b){

int swap;
swap=a;
a=b;
b=swap;

}


int main(){
input();
output();
return 0;
}
Last edited on
Line 27 is before the loop starts, it uses the size of the very first string.
 
    int size=vec[0].size();


It should be inside the loop,
 
    int size = vec[a].size();
Topic archived. No new replies allowed.