fork download
  1. #include <iostream>
  2. #include <fstream>
  3. #include <string>
  4. #include <algorithm>
  5.  
  6. using namespace std;
  7.  
  8. struct Node{
  9. string data;
  10. int lineNum;
  11. bool printed = false;
  12. Node* left;
  13. Node* right;
  14. };
  15.  
  16. Node* GetNewNode(string data, int lineNum){
  17. Node* newNode = new Node();
  18. newNode->data=data;
  19. newNode->lineNum=lineNum;
  20. newNode->left = newNode->right = NULL;
  21. return newNode;
  22. }
  23.  
  24. Node* Insert(Node* rootPtr,string data,int lineNum){
  25. if(rootPtr == NULL){
  26. rootPtr = GetNewNode(data,lineNum);
  27. for (int i =0; rootPtr->data[i]; i++){
  28. while(ispunct(rootPtr->data[i]))
  29. rootPtr->data.erase(i,1);
  30. }
  31. rootPtr->data = rootPtr->data.substr(0,10);
  32.  
  33. return rootPtr;
  34. }
  35. else if(data<= rootPtr->data){
  36. rootPtr->left = Insert(rootPtr->left,data,lineNum);
  37. for (int i =0; rootPtr->data[i]; i++){
  38. while(ispunct(rootPtr->data[i]))
  39. rootPtr->data.erase(i,1);
  40. }
  41. rootPtr->data = rootPtr->data.substr(0,10);
  42. }
  43. else {
  44. rootPtr->right = Insert(rootPtr->right,data,lineNum);
  45. for (int i =0; rootPtr->data[i]; i++){
  46. while(ispunct(rootPtr->data[i]))
  47. rootPtr->data.erase(i,1);
  48. }
  49. rootPtr->data = rootPtr->data.substr(0,10);
  50.  
  51. }
  52. return rootPtr;
  53. }
  54.  
  55. void inOrderPrint(Node *rootPtr ) {
  56. //ofstream outputFile;
  57. //outputFile.open("Output.txt");
  58.  
  59. if ( rootPtr != NULL ) {
  60. inOrderPrint( rootPtr->left );
  61. if (rootPtr->printed)
  62. cout << rootPtr->lineNum;
  63. else{
  64. cout << (rootPtr->data)<<" " << rootPtr->lineNum <<endl;
  65. rootPtr->printed = true;
  66. }
  67. //outputFile << (rootPtr->data)<<rootPtr->lineNum <<endl;
  68. inOrderPrint( rootPtr->right );
  69. }
  70. //outputFile.close();
  71. }
  72.  
  73.  
  74. int main(){
  75. char c;
  76. int counter = 1;
  77. string word;
  78. ifstream inFile;
  79. Node* rootPtr = NULL; // Pointer to the root node
  80.  
  81. inFile.open("example.txt");
  82. if (!inFile)
  83. cout << "Unable to open text file";
  84.  
  85. while (inFile >> word) {
  86. c = inFile.get();
  87. //cout<<c;
  88. if (word == "#")
  89. break;
  90.  
  91. else if (c=='\n'){
  92. rootPtr = Insert(rootPtr,word,counter);
  93. counter++;
  94. }
  95. else
  96. rootPtr = Insert(rootPtr,word,counter);
  97.  
  98. }
  99. inOrderPrint(rootPtr);
  100. inFile.close();
  101. }
  102.  
Success #stdin #stdout 0s 3432KB
stdin
Standard input is empty
stdout
Unable to open text file