我是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;
}
答案 0 :(得分:0)
在您使用的所有地方出现的问题:
cin >> something;
新行字符仍保留在cin
中,以便您接下来阅读的内容。只要你每次读完一行,就写一下
string trash;
getline(trash, cin);
像:
cin >> something;
string trash;
getline(trash, cin);
然后新行字符将不会保留在cin中,您将从一个新线开始。