Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ssl/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 有没有办法限制用户只输入变量的数值?_C - Fatal编程技术网

C 有没有办法限制用户只输入变量的数值?

C 有没有办法限制用户只输入变量的数值?,c,C,正如您所看到的,我的代码不会限制任何内容,我需要帮助限制字母输入我相信下面的问题回答了您的问题。让我知道这是否有帮助 它使用while循环来确保输入仅为数字,但可以很容易地更改为仅为字符。此外,您还可以将变量设置为仅限数字,例如双精度或整数,就像将其设置为仅限字符串一样 原始答复链接: 从Jesse Good的回答中 我将使用std::getline和std::string读取整行,然后在可以将整行转换为double时才中断循环 #include<stdio.h> void ma

正如您所看到的,我的代码不会限制任何内容,我需要帮助限制字母输入

我相信下面的问题回答了您的问题。让我知道这是否有帮助

它使用while循环来确保输入仅为数字,但可以很容易地更改为仅为字符。此外,您还可以将变量设置为仅限数字,例如双精度或整数,就像将其设置为仅限字符串一样

原始答复链接:

从Jesse Good的回答中

我将使用std::getline和std::string读取整行,然后在可以将整行转换为double时才中断循环

#include<stdio.h>

void main(void)
{   
    int n1,n2,r; // variables

    //this just simply add n1 and n2 and shows the result, i want it
    // to only allow numbers not alphabet
    printf("Enter the first number = ");
    scanf("%d",& n1);
    fflush(stdin);
    printf("Enter the second number = ");
    scanf("%d",& n2);
    fflush(stdin);
    r=n1+n2;
    printf("total = %d ", r);
}

希望这有帮助

读字符串,然后检查字符串是否只包含数字。你们能帮我一个忙吗?因为我需要在周六之前提交:\n你能举个例子吗?或者编辑我的!可能重复的
#include <string>
#include <sstream>

int main()
{
    std::string line;
    double d;
    while (std::getline(std::cin, line))
    {
        std::stringstream ss(line);
        if (ss >> d)
        {
            if (ss.eof())
            {   // Success
                break;
            }
        }
        std::cout << "Error!" << std::endl;
    }
    std::cout << "Finally: " << d << std::endl;
}