Программа должна читать в программе на C ++ из файла cpp и печатать все идентификаторы, не относящиеся к ключевым словам, в текстовый файл.
Сначала в функции загрузки я пытаюсь кодировать 3 различных способа чтения
файл cpp. Но количество строк всегда считается 201 строкой. Реальный
ответ 103 строки.Вторая функция deleteCharacterConstants, почему
это не работает, когда я использую?&& line[b] != '\'' or '''
В-третьих, у меня нет идей для кодирования getIdentifiers, Legal, isNumber,
isKeywords и isDuplicate
функция. Кто-нибудь может мне помочь ?? Если можешь, расскажи мне логику и
образец.Наконец, большое спасибо.
Есть моя полная программа.
#include <iostream>
#include <fstream>
using namespace::std;
// read in a C++ program from a cpp file, and put it to the array "program".
void load(char program[][200], int &numLines);
void deleteComments(char line[]); // if there is a single-line comment in "line", delete it.
void deleteStringConstants(char line[]); // if there are string constants in "line", delete them.
void deleteCharacterConstants(char line[]); // if there are character constants in "line", delete them.
// put all identifiers in "line" into identifiers[ numIdentifiers ].
void getIdentifiers(char line[], char identifiers[][32], int &numIdentifiers);
// if character is a letter, digit or underscore, then return true, otherwise return false.
bool legal(char character);
// print all non-number, non-keyword strings in "identifiers" into a text file.
void store(char identifiers[][32], int numIdentifiers);
bool isNumber(char string[]); // if "string" consists of digits only, then return true, otherwise return false.
bool isKeywords(char string[]); // if "string" is a keyword of C++, then return true, otherwise return false.
// if there is a nonnegtive integer i < pos such that identifiers[ pos ] is equal to identifiers[i],
// then return true; otherwise return false.
bool isDuplicate(char identifiers[][32], int pos);
const char keywords[][20] = { "auto", "break", "case", "char", "const", "continue", "default",
"define", "do", "double", "else", "enum", "extern", "float", "for",
"goto", "if", "int", "long", "register", "return", "short",
"signed", "sizeof", "static", "struct", "switch", "typedef",
"union", "unsigned", "void", "volatile", "while", "bool",
"catch", "class", "const_cast", "delete", "dynamic_cast",
"explicit", "false", "friend", "inline", "mutable", "namespace",
"new", "operator", "private", "protected", "public",
"reinterpret_cast", "static_cast", "template", "this", "throw",
"true", "try", "typeid", "typename", "using", "virtual", "include" };
int main()
{
char program[1000][200];
int numLines = 0;
load(program, numLines); // reads in a C++ program from a cpp file, and put it to the array program.
char identifiers[2000][32];
int numIdentifiers = 0;
for (int i = 0; i < numLines; i++)
{
deleteComments(program[i]); // if there is a single-line comment in program[ i ], delete it.
deleteStringConstants(program[i]); // if there are string constants in program[ i ], delete them.
deleteCharacterConstants(program[i]); // if there are character constants in program[ i ], delete them.
if (strcmp(program[i], "") != 0)
// put all identifiers in program[ i ] into identifiers[ numIdentifiers ].
getIdentifiers(program[i], identifiers, numIdentifiers);
}
// print all non-number, non-keyword strings in "identifiers" into a text file.
store(identifiers, numIdentifiers);
system("pause");
}
void load(char program[][200], int &numLines){
ifstream inFile("test.cpp", ios::in);
if (!inFile)
{
cout << "File could not be opened" << endl;
exit(1);
}
for (int i = 0; !inFile.eof(); i++){
inFile.getline(program[i], 200);
numLines++;
}
inFile.close();
}
void deleteComments(char line[])
{
int i = 0;
while (line[i] != '\0' && (line[i] != '/' || line[i + 1] != '/'))
i++;
if (line[i] == '/' && line[i + 1] == '/')
{
line[i] = '\0';
return;
}
}void deleteStringConstants(char line[])
{
int b = 0;
int e;
while (line[b] != '\0')
{
while (line[b] != '\0' && line[b] != '\'')
b++;
if (line[b] == '\0')
break;
e = b + 1;
if (line[e] == '\0')
break;
while (line[e] != '\0' && (line[e - 1] == '\\' || line[e] != '\''))
e++;
if (line[e] == '\0')
break;
for (int i = b; i <= e; i++)
line[i] = ' ';
b = e + 1;
}
}void deleteCharacterConstants(char line[])
{
int b = 0;
int e;
while (line[b] != '\0')
{
while (line[b] != '\0' && line[b] != '"')
b++;
if (line[b] == '\0')
break;
e = b + 1;
if (line[e] == '\0')
break;
while (line[e] != '\0' && (line[e - 1] == '\\' || line[e] != '"'))
e++;
if (line[e] == '\0')
break;
for (int i = b; i <= e; i++)
line[i] = ' ';
b = e + 1;
}
}
void getIdentifiers(char line[], char identifiers[][32], int &numIdentifiers){
}
bool legal(char character){
return 0;
}
void store(char identifiers[][32], int numIdentifiers)
{
ofstream Result("Words.txt", ios::out);for (int i = 0; i < numIdentifiers; i++) {
for (int j = 0; j <= 32; j++){
Result << identifiers[i][j] << endl;
}
}
cout << endl << endl;
Result.close();
}
bool isNumber(char string[]){
return 0;
}
bool isKeywords(char string[]){
return 0;
}
bool isDuplicate(char identifiers[][32], int pos){
return 0;
}
входной файл cpp:
// Fig. 6.20: fig06_20.cpp
// Demonstrating C++ Standard Library class template vector.
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;
void outputVector( const vector< int > & ); // display the vector
void inputVector( vector< int > &, int start ); // input values into the vector
int main()
{
vector< int > integers1( 7 ); // 7-element vector< int >
vector< int > integers2( 10 ); // 10-element vector< int >
// print integers1 size and contents
cout << "Size of vector integers1 is " << integers1.size()
<< "\nvector after initialization:" << endl;
outputVector( integers1 );
// print integers2 size and contents
cout << "\nSize of vector integers2 is " << integers2.size()
<< "\nvector after initialization:" << endl;
outputVector( integers2 );
// input and print integers1 and integers2
cout << "\nEnter 17 integers:" << endl;
inputVector( integers1, 1 );
inputVector( integers2, integers1.size() + 1 );
cout << "\nAfter input, the vectors contain:\n"<< "integers1:" << endl;
outputVector( integers1 );
cout << "integers2:" << endl;
outputVector( integers2 );
......
содержимое выходного файла должно выглядеть следующим образом:
iostream iomanip vector std outputVector inputVector start main ......
Задача ещё не решена.
Других решений пока нет …