验证用户字符串用户输入

时间:2015-11-28 09:57:42

标签: c++ string c-strings

所以我一直在尝试创建这个程序,使用字符串和字符串类从用户那里获取最多12位数字。我遇到的问题是:

  1. 忽略( - )符号。
  2. 忽略小数点。
  3. 输入超过12位数时发出错误。
  4. 只接受数字(即无字母)
  5. 到目前为止,这就是我所拥有的:

    #include <iostream>
    #include <string>
    #include <cctype>
    #include <iomanip>
    
    using namespace std;
    
    bool test(char [] , int);
    
    int main()
    {
    const int SIZE= 13;
    char number[SIZE];
    int count;
    
    cout<< "Please enter a number up to "<< (SIZE-1) <<" digits long." << endl;
    cout<< "The number may be positive or negative" << endl;
    cout<< "and may include fractions (up to two decimal positions)" << endl;
    cout<< "Sign and decimal dot(.) are not included in the digit count:"<< "\t";
    
    cin.getline (number, SIZE);
    
    if (test(number, SIZE))
        {
        while (number[count]!='\0')
            {
            cout<< "The currency value is: \t $";
            cout<< setprecision(2) << number[count];
            count++;
            }
        }   
    else
        {
            cout << "Invalid number: contains non-numeric digits.";
        }
    
    return 0;
    }
    
    
    
    bool test(char testNum[], int size) 
    {
    int count;
    
    for (count = 0; count< size; count++)
        {
            if(!isdigit(testNum[count]))
                return false;
        }
    
    return true;    
    } 
    

    非常感谢任何帮助,但对我来说最重要的是第4点。无论输入是什么,输出都是“无效数字:......”,我不知道为什么会这样。

1 个答案:

答案 0 :(得分:0)

即使输入较短,您的测试功能也会始终测试13个字符。

而是传递一个字符串并使用基于for循环的范围,以便您只测试有效的字符 - 例如:

bool test(string testNum) 
{
    for (auto c : testNum)
    {
        if(!isdigit(c))
            return false;
    }

    return true;    
} 

此外,您还应该更改主循环(打印值的位置),即使用字符串而不是char-array。

BTW - 请注意,这只会检查数字。您对有效输入格式的描述将需要更复杂的测试功能。

例如,要检查您可以添加的标志:

bool test(string testNum) 
{
    bool signAllowed = true;
    for (auto c : testNum)
    {
        if (c == '-')
        {
            if (!signAllowed) return false;
        }
        else
        {
            if(!isdigit(c)) return false;
        }

        // Sign not allowed any more
        signAllowed = false;
    }

    return true;    
} 

但是你还需要更多的代码来检查点(。)

如果您不想使用基于范围的for循环,可以执行以下操作:

bool test(string testNum) 
{
    for (int i = 0; i < testNum.size(); i++)
    {
        if (testNum[i] == '-')
        {
            // Sign is only allowed as first char
            if (i != 0) return false;
        }
        else
        {
            if(!isdigit(testNum[i])) return false;
        }
    }

    return true;    
}