繁体   English   中英

C++ string -> int 不太好用

[英]C++ string -> int doesn't quite work

我的任务是编写一种 ID 检查器。 用户输入他的 ID 号,它应该检查它是否有效并评估其他一些东西(性别、年龄等)。

ID 号由用户作为字符串给出,如下所示:123456/7890

我的任务是删除“/”,然后将字符串转换为 int 并使用它进行一些基本计算,例如if(%11==0){...} 我被困在字符串到 int 转换上。

这是我的代码:

#include <iostream>
#include <string>
#include <sstream>

using namespace std;

int main()
{
    string id;
    int result;
    cout << "Enter an identification number:" << endl;
    cin >> id;

    //Check if the input has "slash" on the 6th position. If so, consider the input valid and remove the slash.
    if (id.at(6) == '/')
    {
        id.erase(id.begin() +6);
    }else cout << "Invalid input." << endl;

    cout << "\n" << id << endl; //cout the ID number without the slash

    stringstream ss(id); //convert the string to int, so we can use it for calculations
    ss >> result;

    cout << "\n" <<result << endl;

    return 0;
}

这似乎只适用于数字的特定阈值。

正如你在这里看到的:
在此处输入图片说明

所以似乎 int 对于这个来说太小了。 但是 long int 或 unsigned long int 也是如此……请问该怎么办?

提前致谢。

使用long long作为__int64等效项。 也看这个。

使用long long数据类型,因为intlong大小相同

如果您使用 unsigned long long int,则最多可以有 18446744073709551615。

使用 ULLONG_MAX in 检查您平台上的最大值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM