How can I check whether there is a special character in my string when my input stored in a pointer? I tried this code but it seems that it will only check for the first char and not the whole string.
void EmployeeDetails(int count, account_s record[count]){ /* Function to get employee details */
int i;
char ch;
EmployeeName:
for(i = 0; i < count; i++){ // count here is the amount of employee from main function
printf("\nEnter employee name: ");
scanf("%s", record[i].EmpName);
ch = record[i].EmpName[i];
if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')){
You probably want something like this:
void EmployeeDetails(int count, account_s record[count]){ /* Function to get employee details */
int i;
EmployeeName:
for(i = 0; i < count; i++){ // count here is the amount of employee from main function
printf("\nEnter employee name: ");
scanf("%s", record[i].EmpName);
for (j = 0; j < strlen(record[i].EmpName); j++)
{
char ch = record[i].EmpName[j];
if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')){
...
}
But the best way is to use on of the standard functions and replace if((ch >= 'a'
with this:
if (!isalpha(ch)) {
...
Even better: outsource the checking if there are special characters in the string to a function:
Replace the whole for (j =
loop with:
if (ContainsSpecialChars(record[i].EmpName)) {
...
with ContainsSpecialChars
being:
int ContainsSpecialChars(const char name[])
{
// Returns 1 if name contains a special character. Otherwise returns 0.
//
// I let you write this as an exercise
}
Don't forget #include <ctypes.h>
for the isalpha
function.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.