Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a C++ FUNCTION which verifies whether an input string represents a “valid

ID: 3771064 • Letter: W

Question

Write a C++ FUNCTION which verifies whether an input string represents a “valid C++ file name” with file extension cpp. Use the following definition of a “valid C++ file name”: 1) the last four characters of the string must end with “.cpp”, 2) the string must have at least one character before the “.cpp” file extension, and 3) all characters before the file extension must be alphabetic only. For example, “myprog.cpp” is valid. But, “ .cpp”, “.cpp”, “circle.cpx”, “7.cpp”, “a_prog.cpp”, and “aprog.cpp “ are all invalid.

The function takes a single string input parameter and returns a value of type bool, i.e. it returns true only if the input string is a “valid C++ file name” (as defined above). Hint: The ASCII code range for A-Z is 65-90 and a-z is 97-122. Also, you may find the string operations length and substr helpful.

Explanation / Answer

#include <iostream>
#include <string>
using namespace std;
bool check(string name){
int length=name.length();
if(length<=3 || name[length-1]!='p' || name[length-2]!='p'|| name[length-3]!='c' || name[length-4]!='.' )
return false;
for (int i=0;i<length-4;i++){
if(!isalpha(name[i]))
return false;
}
return true;
}

int main() {
   string file_name;
   cin>>file_name;
int length=file_name.length();
//   cout<<length;
//   cout<<str.substr(file_name,3,6);
bool temp = check(file_name);
if(temp)
   cout<<"Valid";
   else
   cout<<"invalid";
   return 0;
}   

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote