I have been asked to write a program to detect which of the following formats are used for an identifier, and then to convert that identifier to the other format:
In Java, a multiword identifier is constructed in the following manner: the first word is written starting from the small letter, and the following ones are written starting from the capital letter, no separators are used. All other letters are small. Examples of a Java identifier are javaIdentifier
, longAndMnemonicIdentifier
, name
, nEERC
.
C++ uses only small letters in its identifiers. To separate words it uses the underscore character ‘_’. Examples of C++ identifiers are c_identifier
, long_and_mnemonic_identifier
, name
(you see that when there is just one word Java and C++ people agree), n_e_e_r_c
.
If it is neither, the program should report an error. Translation must preserve the order of words and must only change the case of letters and/or add/remove underscores.
Input:
The input file consists of several lines that contains an identifier. It consists of letters of the English alphabet and underscores. Its length does not exceed 100.
Output:
If the input identifier is Java identifier, output its C++ version. If it is C++ identifier, output its Java version. If it is none, output 'Error!' instead.
So here's my code in C++; I submitted it on the online judge but it gave the wrong answer. I have no idea what's wrong. It passed all my own test cases.
Can someone help me find the problem?
#include<iostream>
#include<string>
#include <ctype.h>
using namespace std;
void Convert(string input){
string output = "";
string flag = "";
bool underscore = false;
bool uppercase = false;
if ( islower(input[0]) == false){
cout << "Error!" <<endl;
return;
}
for (int i=0; i < input.size(); i++){
if ( (isalpha( input[i] ) || (input[i]) == '_') == false){
cout << "Error!" <<endl;
return;
}
if (islower(input[i])){
if (underscore){
underscore = false;
output += toupper(input[i]);
}
else
output += input[i];
}
else if (isupper(input[i])){
if (flag == "C" || uppercase){
cout << "Error!"<<endl;
return;
}
flag = "Java";
output += '_';
output += tolower(input[i]);
}
else if (input[i] == '_'){
if (flag == "Java" || underscore){
cout << "Error!" <<endl;
return;
}
flag = "C";
underscore = true;
}
}
cout << output <<endl;
}
int main(){
string input;
while (cin >> input)
Convert(input);
return 0;
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…