The string function reverse is supposed to the words in a sentence from a file, for example "This is red" to "red is This."
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
|
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int nwords(string);
string reverse (string);
int main()
{
ifstream myfile;
myfile.open("/Users/Soul/Documents/School/CISC/Assignment9/file.txt");
int numwords;
string next;
getline(myfile,next);
while(myfile){
numwords = nwords(next);
cout <<"Original line: " << next << endl;
cout <<"Number of words: "<< numwords << endl;
cout <<"Reverse version:";
cout << " " <<reverse(next) << endl << endl;
getline(myfile,next);
}
return 0;
}
int nwords(string str){
int nw = 0, nextblank;
nextblank = str.find(" ",0);
while(nextblank>0){
nw++;
str = str.substr(nextblank+1);
nextblank = str.find(" ",0);
}
return nw+1;
}
string reverse (string str) {
string result="", temp;
int ttllen = str.length();
str.insert(ttllen," ");
int nextblank;
nextblank = str.find(" ",0);
while(nextblank>0){
temp = str.substr(0,nextblank);
result.insert(0, " ");
result.insert(0,temp);
str = str.substr(nextblank+1);
nextblank = str.find(" ",0);
}
return result;
}
|
But the output has a habit with removing the last word. For some reason, it works fine when I use cin instead of using a file.
Output:
Last login: Wed Dec 10 16:44:45 on ttys000
/Applications/CodeBlocks.app/Contents/MacOS/cb_console_runner DYLD_LIBRARY_PATH=$DYLD_LIBRARY_PATH:. /Users/Soul/Documents/School/CISC/Assignment9/bin/Debug/Assignment9
Christians-MacBook-Pro:~ Soul$ /Applications/CodeBlocks.app/Contents/MacOS/cb_console_runner DYLD_LIBRARY_PATH=$DYLD_LIBRARY_PATH:. /Users/Soul/Documents/School/CISC/Assignment9/bin/Debug/Assignment9
Original line: This is assignment number 9
Number of words: 5
number assignment is This
Original line: Computer Science is a very detailed discipline
Number of words: 7
detailed very a is Science Computer
Original line: Although there are many classrooms in Ingersoll Hall some of the classrooms are not available
Number of words: 15
not are classrooms the of some Hall Ingersoll in classrooms many are there Although
Original line: The history of the world is a subject that continues to develop everyday
Number of words: 13
develop to continues that subject a is world the of history The
Original line: Birthday parties are fun
Number of words: 4
are parties Birthday
Original line: This course was easy
Number of words: 4
was course This easy
Original line: The president of Brooklyn College is Karen Gould
Number of words: 8
Karen is College Brooklyn of president The
Original line: I know who Daniel Malloy is.
Number of words: 6
Reverse version: is. Malloy Daniel who know I
Process returned 0 (0x0) execution time : 0.022 s
Press ENTER to continue.
Any help is appreciated