2013-07-07 5 views

답변

1

입력이 C++ 문자열이라고 가정 할 때, 다음은 당신을 끌어들일 수있는 재귀 적 솔루션의 시작입니다. 나는 요아킴과 라센의 의견에 동의한다. 아래의 접근법은 rasen이 제안한 선을 따라 더 많이 이어집니다.

키 포함 항목은 cctype입니다. 주어진 문자가 숫자인지 아닌지에 대한 부울 검사를 제공합니다.

작성된 것처럼 코드는 숫자가 아닌 문자가 발생하면 NULL 값을 반환하며 반환 된 숫자에는 0으로 표시됩니다. 필요에 따라이 구현을 수정해야합니다. 예를 들어, "23.1"은 2301로 되돌아 가고, "." 0으로 대체됩니다.

이것은 정확히 원하는 것은 아니므로 논리를 구현하려는 방법, 지정된 특수 문자를 반환하는 방법, 숫자가 아닌 문자가 나오는 경우 등을 생각해보십시오. 그런 다음이 반환 값에 지정된 char이 있는지 검색하여 주어진 입력 문자열이 int 데이터 유형으로 변환 할 수 있는지 여부를 알려주는 부울 함수의 기초를 제공 할 수 있습니다.

MAIN.CPP (아래)의 출력은 아래

Here is the integer: Invalid character, entry must be a number: 
2301 
Here is the integer: 22 
Here is the integer: 0 
Here is the integer: 1 
Here is the integer: 32 

코드 :

// main.cpp 
// Created by bruce3141 on 7/7/13. 

/* Numeric Conversion (string to int) 
* ---------------------- 
* Demonstrates a recursive implementation of converting a string into 
* its representation as an int. Provides feedback to the user on invalid 
* entries, using isdigit() from the <cctype> import, where a invalid 
* character (a non-digit) is encountered. 
*/ 

#include <iostream> 
#include <string> 
#include <cctype> 
using namespace std; 


/* Function prototype */ 
int stringToInt(string str); 


// Main.cpp tests a few cases below: 
int main() { 
    int n = 5; 
    string strNumbers[5] = {"23.1", "22", "-0", "+1", "32"}; 
    for (int i = 0; i < n; i++) { 
     cout << "Here is the integer: "<< stringToInt(strNumbers[i]) <<endl; 
    } 
    return 0; 
} 



/* Convert from string -> int. The code is longer because of the possibility 
* that we might have a '-' or '+' preceding the integer input, and then of 
* course multiple digits in combination with the '-' or '+' signs: 
*/ 
int stringToInt(string str) { 

/* Get the number of characters in the string: */ 
int nS = str.length(); 

/* Base Case #1: a single positive integer as input: */ 
if (nS == 1) { 
    /* This basic version provides a liitle feedback on 
    * invalid entries, using isdigit() from the <cctype> 
    import: */ 
    if (!isdigit(str[0])) { 
     cout << "Invalid character, entry must be a number: "<<endl; 
     return NULL; 
    } else { 
     /* We have to subtract the ASCII code for the character '0' so 
     that the string displays as a number in the proper range: */ 
     return str[0]-'0'; 
    } 

    /* Base Case #2: a single negative integer as input, here 
    * we deal with the possibility that a '-' precedes a number: */ 
} else if (nS == 2 && str.substr(0,1) == "-") { 
    /* Below, subtract the ASCII code for the character '0' then 
    * multiply by (-1) since the number is negative: */ 
    return (str[1] - '0')*(-1); 

    /* Base Case #3: a single postive integer as input, as indicated 
    * by a '+' character: */ 
} else if (nS == 2 && str.substr(0,1) == "+") { 
    /* Below, subtract the ASCII code for the character '0': */ 
    return (str[1] - '0'); 

    /* Below is the recursive step for negative numbers with more 
    * than one digit: */ 
} else if (nS >= 2 && str.substr(0,1) == "-") { 
    int n1 = stringToInt(str.substr(0,nS-1))*10; 
    int n2 = stringToInt(str.substr(nS-1,nS)); 
    return n1 - n2; 

    /* Below is the recursive step for positive numbers with a 
    * preceding '+' character and with more than one digit: */ 
} else if (nS >= 2 && str.substr(0,1) == "+") { 
    int n1 = stringToInt(str.substr(0,nS-1))*10; 
    int n2 = stringToInt(str.substr(nS-1,nS)); 
    return n1 + n2; 
} 

/* Below is the recursive step for positive numbers with more 
* than one digit, but with no preceding '+' character: */ 
else { 
    int n1 = stringToInt(str.substr(0,nS-1))*10; 
    int n2 = stringToInt(str.substr(nS-1,nS)); 
    return n1 + n2; 
} 

}

2

읽어 정말 많은 당신이 할 수있는이 아니다. 부동 소수점 숫자를 정수 변수로 읽으려고하면 스트림 (예제의 숫자 포함)은 정수로 1을 읽습니다. 이는 물론 오류입니다.

일 수 있습니다. 다음 문자는 peek이며, 기대하는 바가 없는지 확인합니다.

+0

엿보기 후에 다음 문자가 예상되는지 여부를 확인하는 방법은 무엇입니까? 감사. – user1899020

0

문자열로 데이터를 입력 한 다음 올바른 형식인지 분석 할 수 있습니다. 그렇다면 원하는 유형으로 변환하십시오.

관련 문제