【问题标题】:C++ string to int without using atoi() or stoi() [duplicate]不使用 atoi() 或 stoi() 将 C++ 字符串转换为 int [重复]
【发布时间】:2013-10-19 03:36:17
【问题描述】:

您好,我是 C++ 新手,正在尝试执行一项任务,我们从 txt 文件中读取大量数据,格式为

 surname,initial,number1,number2

在有人建议将 2 个值读取为字符串然后使用 stoi() 或 atoi() 转换为 int 之前,我寻求帮助。这很好用,除了我需要使用这个参数“-std=c++11”进行编译,否则会返回错误。这在我自己的计算机上可以处理“-std=c++11”不是问题,但不幸的是,我必须在其上展示我的程序的机器没有这个选项。

如果有另一种方法可以将字符串转换为不使用 stoi 或 atoi 的 int?

这是我目前的代码。

while (getline(inputFile, line))
{
    stringstream linestream(line);

    getline(linestream, Surname, ',');
    getline(linestream, Initial, ',');
    getline(linestream, strnum1, ',');
    getline(linestream, strnum2, ',');
    number1 = stoi(strnum1);
    number2 = stoi(strnum2);

    dosomethingwith(Surname, Initial, number1, number2);
}

【问题讨论】:

  • 首先,atoi 不需要 -std=c++11。但我会避免使用atoi,因为它不允许任何错误检查。更好的解决方案是strtoi
  • 当你想要的是istringstream 时,这种使用stringstream 的狂热是什么? (我经常看到,我不明白为什么有人会这样做。)
  • 另外,对于这种格式,我会使用 boost::split 之类的东西,而不是 istringstream(这仍然存在转换为 int 的问题)。

标签: c++ string int type-conversion atoi


【解决方案1】:

我认为你可以编写自己的 stoi 函数。 这是我的代码,我测试过了,很简单。

long stoi(const char *s)
{
    long i;
    i = 0;
    while(*s >= '0' && *s <= '9')
    {
        i = i * 10 + (*s - '0');
        s++;
    }
    return i;
}

【讨论】:

  • 首先,他没有char const*,而是std::string。其次,这些功能需要更多的错误检查才能有用。
【解决方案2】:

您已经在使用 stringstream,它为您提供了这样的“功能”。

void func()
{
    std::string strnum1("1");
    std::string strnum2("2");
    int number1;
    int number2;
    std::stringstream convert;

    convert << strnum1;
    convert >> number1;

    convert.str(""); // clear the stringstream
    convert.clear(); // clear the state flags for another conversion

    convert << strnum2;
    convert >> number2;
}

【讨论】:

  • 虽然可以很复杂,但为什么要简单?您不需要(也不一定需要)双向stringstream。只需使用istringstream,用正确的字符串初始化。
猜你喜欢
  • 1970-01-01
  • 2020-08-27
  • 2018-05-31
  • 1970-01-01
  • 2022-07-05
  • 2013-09-01
  • 2012-10-13
  • 2015-09-07
  • 1970-01-01
相关资源
最近更新 更多