Im pulling a text file – it will be input by user
currently its just pulling from C:\Dump\test.txt
I want to re-arrange the words in said file
This is what i have so far
static string revFunc(string a)
{
ifstream inp;
inp.open(a, std::ios::in);
string lines;
while(getline(inp, lines)){
istringstream iss(lines);
string outstr;
string word;
iss >> outstr;
if (inp >> word){
outstr = word + ' ' + outstr + ' ';
cout << outstr;
}
}return 0;
}
the string a is the path to file on the hdd
this will parse 2 lines backwards
there are ~13 lines in the tester file
this is from int main()
int main(){
string file;
int words = 0;
int lines = 0;
int choice;
system("cls");
cout << "Enter Filename: " << endl;
file = "C:\\Dump\\test.txt";
cout << file;
//cin >> file;
cout <<"MENU"<<endl;
cout <<"----------------------------------" << endl;
cout << "1. Count Words" << endl;
cout << "2. Count Lines" << endl;
cout << "3. Index Words" << endl;
cout << "4. Average Length of Words" << endl;
cout << "5. Print Text File to Screen" << endl;
cout <<"----------------------------------" << endl;
cout << "??: ";
cin >> choice;
switch(choice){
case 1: cout << "Words: " << wordFunc(file) << endl;
system("PAUSE");
break;
case 2: cout << "Lines: " << lineFunc(file, lines) << endl;
system("PAUSE");
break;
case 3: indexFunc(file);
system("PAUSE");
break;
case 4: cout << "Average Length: " << avgWordFunc(file) << endl;
system("PAUSE");
break;
case 5: printStrFunc(file);
cout <<endl;
system("PAUSE");
break;
case 6: revFunc(file);
cout << endl;
system("PAUSE");
break;
}
return 0;
}
Then the program aborts – im sure due to bad coding 🙂
Any help pointing out my ridiculous mistakes are appreciated
You say your
refFuncreturns astring, but the return value is0(anint, not astring).This will result in a problem as the program tries to use a string object, and finds “garbage” (that has been allocated in anticipation of a string but has not been filled with the correct bits of a string).
To fix, you either need to change the return type to
intor change the return value to a valid string (e.g."").Alternatively, if you are not using the return value (as is the case in your example), you can change the return type to
void. In this case, use onlyreturn;(note: no value after return), or you can leave the whole return statement out;NOTE: To prevent from future such mistakes, configure your compiler to compile with maximum warnings setting and possibly with warnings turned into errors. This will prevent you from compiling your program without at least the compiler telling you you are doing something (most likely) incorrectly
NOTE: Do not learn the habit of using
system()even for pausing your application. It is platform dependent, and can introduce a security risk (although I don’t think you will worry about that for a while)