4

嗨,我是 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);
}
4

2 回答 2

4

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

long stoi(const char *s)
{
    long i;
    i = 0;
    while(*s >= '0' && *s <= '9')
    {
        i = i * 10 + (*s - '0');
        s++;
    }
    return i;
}
于 2013-10-11T07:11:55.577 回答
0

您已经在使用 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;
}
于 2013-10-11T06:43:02.463 回答