Я новичок в C ++, и я читал различные проблемы и решения, но я все еще не могу заставить свой код работать!Проблема в том, что если я не включаю закомментированные cin.clear () или cin.synch (), мой код не останавливается в начале getlineКогда я их добавляю, он зацикливается бесконечно.Есть ли что-то, что я не в том числе?Вот мой исходный код:
#include <iostream>
#include <fstream>
#include <string>
#include <cctype>
using namespace std;
int main() {
string inputFileName, outputFileName, inData, outData, inWord, outWord;
ifstream inFile, testStream;
ofstream outFile;
bool outPutOpened = false;
char outChar;
int shiftNum = 0, idx = 0;
do {
inWord.clear();
outWord.clear();
//cin.clear();
//cin.sync();
cout << "Available options: " << endl;
cout << "1. ENCRYPT - Encrypt a file using Caesar Cypher" << endl // menu
<< "2. Quit - Exit the program" << endl << endl;
cout << " Enter keyword or option index: ";
getline(cin, inWord); // get option
outWord.resize(inWord.length());
transform(inWord.begin(), inWord.end(), outWord.begin(), ::toupper); //capitalize
if (outWord.compare("ENCRYPT") == 0 || outWord.compare("1") == 0) {
cout << "CAESAR CYPHER PROGRAM" << endl
<< "======================" << endl << endl;
do {
cout << "Provide the input file name: ";
getline(cin, inputFileName);
inFile.open(inputFileName.c_str());
if (inFile.fail()) {
cout << "Cannot open file, please try again!" << endl;
inFile.clear();
}
}
while (!inFile.is_open());
getline(inFile, inData);
do {
cout << "Provide the output file name: ";
cin >> outputFileName;
testStream.clear();
testStream.open(outputFileName.c_str());
if(testStream.good()) {
cout << "That file already exists, choose another" << endl;
testStream.clear();
testStream.close();
}
else {
testStream.clear();
testStream.close();
outFile.open(outputFileName.c_str());
if (outFile.good()) {
outPutOpened = true;
}
}
}
while (!outPutOpened);
cout << "Enter the shift number: ";
cin >> shiftNum;
for (idx = 0; idx <= inData.length() - 1; idx++) {
if (inData[idx] >= 'a' && inData[idx] <= 'z') {
outChar = (((inData[idx] - 'a') + shiftNum) % 26) + 'a';
outFile.put(outChar);
}
else if (inData[idx] >= 'A' && inData[idx] <= 'Z'){
outChar = (((inData[idx] - 'A') + shiftNum) % 26) + 'A';
outFile.put(outChar);
}
else {
outFile.put(inData[idx]);
}
}
}
else if (outWord.compare("2") == 0 || outWord.compare("QUIT") == 0) {
break;
}
else {
cout << inWord << " is an unrecognized option, please try again"
<< endl;
}
}
while (outWord.compare("2") || outWord.compare("QUIT"));
return 0;
}