2014-05-17 3 views
0

텍스트 문서에서 이름, 공백 및 십진수 값으로 작성된 정보를 읽는 것으로 가정합니다. 예를 들어, 파일에서 라인이있을 수 있습니다입력 유효성 검사?

타이거 56.3

내가 그 첫 번째 부분을 확인하기 만하면 소수점을 포함한 숫자 만 포함 된 문자와 두 번째 부분을 포함하는 문자열입니다. 지금까지 다음 기본 코드가 있습니다 :

ifstream input("data.txt"); 
while(!input.eof()) 
{ 
    string name; 
    double score; 

    input >> name; 
    input >> score; 

} 

어떻게해야합니까?

+0

일반적인 방법은 파일을 텍스트 (한 번에 한 줄씩)로 읽은 다음 수동으로 토큰 화하고 렉싱하는 것입니다. C++ 'istream'포맷터는 강력한 입력 검증에 실제로 적합하지 않습니다. – Mankarse

+0

간단합니다. 줄을 문자열로 입력하십시오. 공간으로 두 부분으로 나눕니다. 처음부터 반복하여 문자가 아닌 문자와 두 번째 숫자가 아닌지 확인하십시오. –

+0

당신은 정규 표현식 라이브러리 –

답변

1

새로운 C++11Regular Expressions을보고 싶을 수 있습니다. 입력 확인과 같은 작업을 위해 특별히 만들어졌습니다.

최소한의 예는 문자열은 다음과 같이 수있는 유일한 숫자와 + 또는 - 징후가 포함되어 있는지 확인합니다 : 당신은 아주 최근의 컴파일러 (GCC 내 생각 4.9)가 필요하지만

#include <iostream> 
#include <regex> 
#include <string> 

int main() 
{ 
    std::string testString; 
    std::regex integer("(\\+|-)?[[:digit:]]+"); 
    input >> testString; 
    if(std::regex_match(input, integer)) 
     std::cout << "Valid number" << std::endl; 
    else 
    { 
     std::cout << "No valid number" << std::endl; 
    } 
} 

, 사용할 수 있습니다. 이 기능을 사용할 수없는 경우 Boost Regex Library을 사용할 수 있으며 매우 유사한 인터페이스를 제공합니다.

+0

을 사용할 수 있습니다. C++ 11을 사용하는 방법은 없나요? 필자가 작성한 프로그램은 대학의 컴퓨터에서 실행되어야하며 C++ 98을 사용하고 있다고 생각합니다. –

+0

@GdgamesGamers, 만약 그들이 boost가 설치되어 있다면, 새로운'C++ 11' 라이브러리와 유사한 boost regex library를 사용할 수 있습니다. 이 기능을 사용할 수 없다면 문자를 반복하여 검사를 하드 코딩해야한다고 생각합니다. – Haatschii

+0

@GdgamesGamers 답변에 링크가 추가되었습니다. – Haatschii

0

문자열로 데이터를 읽고 거기에서 구문 분석 :

template<class iter> 
bool is_alphabetic(iter beg, iter end) 
{ 
    bool found_number = true; 
    while (beg != end && (found_number = !std::isdigit(*beg++))) 
     ; 
    return found_number; 
} 

template<class container> 
bool is_alphabetic(container& c) 
{ 
    return is_alphabetic(c.begin(), c.end()); 
} 
0
#include<iostream> 
#include<string> 
using namespace std; 

int validate(string,string); 

int main(){ 

    string s; 
    string d; 

    cin>>s>>d; 

    if(validate(s,d)) cout<<"ok"; 
    else cout<<"not ok"; 


} 


int validate(string s, string d){ 


    for(int i=0;i<s.size();++i){ 
      //all either small letter or capital letter else error 
     if(!((s[i]>='A' && s[i]<='Z') || (s[i]>='a' && s[i]<='z'))){ 
      return 0; 

     } 

    } 
    int f=0; 

    for(int i=0;i<d.size();++i){ 
      //either digits or decimal 
     if(!((d[i]>='0' && d[i]<='9') || d[i]=='.')){ 
      return 0; 
     } 

      //if decimal already present and again decimal its an error ex. 123.23.23 
     if(d[i]=='.' && f==1) return 0; 
      //flag indicating decimal present 
     if(d[i]=='.') f=1; 

     if(d[i]>='0' && d[i]<='9' && f==1) f=2; // validate decimal like 132. (not valid) 
    } 

    if(f==1) return 0; 

    return 1; 
} 
0
여기

간단한 코드가있다 :

while(!input.eof()) 
{ 

    string name; 
    string score; 

    input >> name; 
    for (int i=0; i<name.size() ; i++) { 
     if ((name [i] >= 'A' && name [i] <= 'Z') || (name [i] >= 'a' && name [i] <= 'z') || (name [i] == '_')) { 
      continue; 
     } else { 
      cout <<"Name is not valid!"; 
      break; 
     } 
    } 

    input >> score; 
    for (int j=0; j<score.size() ; j++) { 
     if ((score [j] >= '0' && score [j] <= '9') || (score[j]=='.')) { 
      continue; 
     } else { 
      cout <<"Number is not valid!"; 
      break; 
     } 
    } 
} 
다음
std::string name, score_str; 
while (input >> name >> score_str) 
{ 
    if (!is_alphabetic(name) || !is_decimal_number(score_str)) { 
     // error 
    } 
    else { 
     // convert score_str to a double and assign it to score 
    } 
} 

is_alphabetic의 예