| upain21 (1) | |
|
When I open the file in my code, it does not seem to be able to read anything that's in it. I used fstream inputfile then inputfile.open(file). The file seems to be opened but when I try to get char c to equal the first character in the file, it doesn't seem to work. c should initially "<" but xcode shows that it equals "_" or "/". I continue running the program but no matter what, my codes doesn't seem to be able to read anything in the text file I opened. What did I do wrong? here is my code: #include <iostream> #include <string> #include <fstream> using namespace std; int main() { fstream testFile; string encryptedFile; string file; string fileName; cout << "Please enter the name of the file:"; cin >> fileName; string line; fstream inputfile; inputfile.open(fileName.c_str()); // opens the file if (inputfile.is_open()) { // only operates when there are still lines in the file while (inputfile.get()) { // get the line, put into the variable "line" getline (inputfile, line); bool right = false; bool hasDirection = false; bool hasShift = false; int shift = 0; for (int i=0; i < line.length(); i++) { char c = line.at(i); if(c == ' ') { continue; } if(c == '+') { shift = 0; right = false; hasDirection = false; hasShift = false; } else if(c == '<') { right = false; hasDirection = true; } else if(c == '>') { right = true; hasDirection = true; } //if between 0 and 9 else if(hasDirection && c >= 48 && c <= 57) { if(shift > 0) { shift = shift*10 + c - 48; //more than one digit } else { shift = c - 48; hasShift = true; } } else { if(!hasDirection || !hasShift) { cout << "*** ERROR: No shift value as expected ***" << endl; cout << "Special character: "; if(!hasDirection) cout << "+"; else if(right) cout << ">"; else cout << "<"; cout << " requires a numeric following it." << endl; break; } else if((c >= 97 && c <= 122) || (c >= 65 && c <= 90)) { //if it's a char if(c >= 97) { //if lowercase, make it upper c -= 32; } char newchar = c + shift; if(!right) { newchar = c - shift; //other way on ascii newchar = newchar - 65; } if(newchar < 0) { //overflow newchar = newchar % 26; newchar = 26 - newchar; } else { newchar = newchar % 26; } newchar = newchar + 65; cout << newchar; } //prints two end-of-line characters else if(c=='#') { cout << endl << endl; break; } } } } inputfile.close(); } else { cout << "*** ERROR: Error in opening file ***" << endl; cout << "You entered an invalid file name. Please try again." << endl; } } here is what the file contains: <25CNM'S OZX ZMX ZSSDMSHNM SN SGD LZM ADGHMC SGD BTQSZHM.# >20ZXAYZ SK < EUA YNUARJT'Z HK NKXK.# >7IETR BM LTF. HY TEE MAX ZBG CHBGML BG TEE MAX IETVXL BG TEE MAX PHKEW, LAX ATW MH PTED >14UZFA YUZQ. IQ'XX MXIMKE TMHQ BMDUE. >23URXQG XS WKH XVXDO VXVSHFWV.# | |
|
|
|