将文件行的每个元素转换为整数

时间:2013-12-22 18:48:10

标签: c++ string file

我有一个名为numbers.txt的文件,有几行数字。我只是想将每个数字转换为整数并将其打印出来。

if (numbers.is_open()) {
    while (std::getline(numbers, line)) {
        for (int i = 0; i < line.length(); i++) {
            number = atoi((line.at(i)).c_str());
            std::cout << number;
        }
    }
    numbers.close();

有人可以解释为什么这对我不起作用吗?

2 个答案:

答案 0 :(得分:0)

您的内部for循环遍历行中的每个字符,这是不必要的,假设您要将整行视为单个数字。 atoi()函数对整个c字符串进行操作,而不仅仅是单个字符。所以,你可以摆脱for循环和.at(i),并做这样的事情:

if (numbers.is_open()) {
    while (std::getline(numbers, line)) {                                     
        int number = atoi(line.c_str());
        std::cout << number << std::endl;                            
    }
    numbers.close();
  }
}

编辑(w.r.t评论#0)

要单独解释每个字符,您可以执行此操作(尽管可能有更清晰的实现):

if (numbers.is_open()) {
    while (std::getline(numbers, line)) {
      for (int i = 0; i < line.length(); i++) {                                                     
        int number = atoi(line.substr(i, 1).c_str());
        std::cout << number << endl;
        }
    }
    numbers.close();
  }

如果您可以保证文件中只有数字,您也可以执行以下转换:

int number = line.at(i) - '0';

答案 1 :(得分:0)

您的初始代码甚至不应该编译,因为std::string::at(size_t pos)不会返回std::string;它返回一个原始字符类型。字符没有方法 - 没有char::c_str()方法!

如果您的上述评论是正确的,并且您希望将个别字符视为数字,我建议如下:

if (numbers.is_open())
{
    while (std::getline(numbers, line))
    {
        auto i = line.begin(), e = line.end(); // std::string::const_iterator
        for (; i != e; ++i)
        {
            if (std::isdigit(*i))
            {
                // Since we know *i, which is of type char, is in the range of
                // characters '0' .. '9', and we know they are contiguous, we
                // can subtract the low character in the range, '0', to get the
                // offset between *i and '0', which is the same as calculating
                // which digit *i represents.
                number = static_cast<int>(*i - '0');
                std::cout << number;
            }
            else throw "not a digit";
        } // for
    } // while
    numbers.close();
} // if
相关问题