I try to find the shortest and the longest word from a sentence that i read from a file.
I just need some idea how to do this.
Please do not put any code just ideas.
Well how I would do it is first open the file.
Read in word by word and store the longest and shortest based on size().
So pseudo-code:
1 2 3 4 5 6 7
open(file);
read(file) -> variable;
check( variable.size() )
if > than largest_word_variable.size(), replace largest_word_variable
if < than smallest_word_variable.size(), replace smallest_word_variable
finished ? (end loop) : (goto read);
print largest and smallest word.
I do not understand the part with the variable.
I open the file " ofstream myfile ("exercise.txt");
I read a file with fgets or fread?
And i put what i read in a variable?
#include <iostream>
#include <fstream>
#include <string>
usingnamespace std;
int main () {
string mystring;
//ofstream myfile ("exercise.txt");
ifstream infile("exercise.txt");
// You should create the file in the directory with the executable before hand.
if ( infile.is_good() )
{
//ifstream infile("exercise.txt"); // Don't open inside a block. Will dissapear at its end.
infile >> mystring;
cout >> mystring; // cout uses <<, cin uses >>
}
else cout << "Unable to open file";
//myfile.close();
infile.close();
cin.get();
return 0;
}
I modified your code a little and now is compiling ok but I reads me only a strange character from my file.
The sentence is" I have to find the longest and the shortest word from a sentence."
and the output shows me only the first character" I."
#include <iostream>
#include <fstream>
#include <string>
usingnamespace std;
int main () {
string mystring;
//ofstream myfile ("exercise.txt");
ifstream infile("exercise.txt");
// You should create the file in the directory with the executable before hand.
if ( infile.is_open() )
{
//ifstream infile("exercise.txt"); // Don't open inside a block. Will dissapear at its end.
infile >> mystring;
cout << mystring; // cout uses <<, cin uses >>
}
else cout << "Unable to open file";
//myfile.close();
infile.close();
cin.get();
return 0;
}
infile.is_good() wrutes me that is not valid soI had to replace it.