如何修复此字符串验证(电话目录系统)

时间:2019-01-10 14:43:13

标签: c++

我说的是在void enter()中进行字符串验证,我试图做的是创建一个系统,如果有人不小心在输入名称字段中输入了数字,他们需要再次写出

im根本无法解决此字符串验证问题。

我尝试过类似 在cout <<“输入名称”之后;

 for(int i=0;i<strlen(name);i++)
 {
  gets(name);
  if(isalpha(name[i]))
  cout<<"There is a number in the input , try again";
 }


include<fstream.h>
include<stdio.h>
include<conio.h>
include<string.h>
include<stdlib.h>

class Directory
 {
 char name[20];
 char num[30];
 char address[50];
  public:
  void enter()
 {
  cout<<"Enter name: "<<endl;
  gets(name);
  cout<<"Enter number: "<<endl;
  gets(num);
  cout<<"Enter address: "<<endl;
  gets(address);
 }

它确实起作用了,但是如果我输入一个名称“ mar3”,现在我必须输入四次Mark才能记录下来。

1 个答案:

答案 0 :(得分:1)

我认为这是您想要做的。您要重新输入名称,直到满足您的要求为止。

bool validate(char name[])
{
    for(int i=0;i<strlen(name);i++)
        if(isalpha((unsigned char)name[i]))
        {
            cout<<"There is a number in the input , try again";
            return 0;
        }
    return 1;
}

在读名字的时候这样做。

gets(name);
while(!validate(name))
{
    gets(name);
}

UPD: 使用字符串和getline读取。

#include<fstream>
#include<cstdio>
#include<cstring>
#include<stdlib.h>
#include<stdio.h>
#include<iostream>
using namespace std;
bool validate(string name)
{
    for(int i=0;i<name.length();i++)
        if(isalpha(name[i]))
        {
            cout<<"There is a number in the input , try again\n";
            return 0;
        }
    return 1;
}
class Directory
{
    string name,num,address;
    public:
    void enter()
    {
        cout<<"Enter name: "<<endl;
        getline(cin,name);
        while(!validate(name))
        {
            getline(cin,name);
        }
        cout<<"Enter number: "<<endl;
        getline(cin,num);
        cout<<"Enter address: "<<endl;
        getline(cin,address);
    }
};
  

在这里您还想限制可以为该验证器创建另一个验证器的名称或数字的长度