atoi()不使用std :: string :: substr()

时间:2014-04-15 04:46:16

标签: c++ string atoi

这是我的代码片段:

#include <iostream>
#include <fstream>
#include <string>
#include <stdlib.h> // atoi()


int main() {

    std::string line;

    std::ifstream numbers("numbertest.txt");

    if (numbers.is_open()) {
        while (std::getline(numbers, line)) {
            for (int i = 0; i < line.length() - 4; i++) {
                for (int n = 0; n < 5; n++) {
                    std::cout << atoi((line.substr(i, 5)[n]).c_str());
                }

我想从文件中以5个为一组的数字进行操作。为什么atoi()不在这里工作?它说&#34;表达式必须有类型&#34;在atoi线的第二个括号下。

2 个答案:

答案 0 :(得分:4)

line.substr(i, 5)line位置i创建一个包含5个字符的临时std :: string

std::string foo = "hello world";
int i = 2;
std::cout << foo.substr(2, 5) << '\n';

会打印&#34; llo wo&#34;。

[n]运算符返回子字符串的n字符,其类型为char,然后您在该字符上调用.c_str() 而不是子串。

您可以使用std::stoi完全避免使用.c_str(),例如

std::cout << "line.substr(i, 5) = " << line.substr(i, 5) << '\n';
std::cout << std::stoi(line.substr(i, 5));

aoti和stoi都将数字的字符串表示作为输入并返回数值。例如:

std::string input = "123a";
// std::cout << input * 10 << '\n'; // illegal: input is a string, not a number.
int i = std::stoi(input); // converts to integer representation, i.e. 123
std::cout << i * 10 << '\n'; // outputs 1230

-----编辑-----

你实际上是在问所有错误的问题。你想要做的是采用输入模式并输出其中5个字符的所有模式。

输入示例:&#34; 1020304050&#34; 输出示例:10203 02030 20304 03040 30405 04050

您不需要将这些转换为数字来输出它们,您只需输出字符即可。原始代码的问题不在于转换是不正确的运算符序列。

std::substring是昂贵的,它必须创建一个新的临时字符串,将原始字符复制到其中,然后将其返回,并为每次调用执行此操作。

以下内容应达到您的目标:

while (std::getline(numbers, line)) {
    for (size_t i = 0; i < line.length() - 4; i++) {
        for (size_t n = 0; n < 5; n++) {
            std::cout << line[i + n];
        }
        std::cout << '\n';
    }
}

如果你真的想调用substr,你也可以将其实现为

while (std::getline(numbers, line)) {
    for (size_t i = 0; i < line.length() - 4; i++) {
        std::cout << line.substr(i, 5) << '\n';
    }
}

这是一个工作示范:http://ideone.com/mXv2z5

答案 1 :(得分:1)

尝试atoi( line.substr(i,5).c_str() )

或者如果你想要每个角色

std::cout << ((line.substr(i, 5)[n]) - '0');

甚至更好

std::cout << (line[i+n]) - '0');

请注意:atoi ascii为整数。它将ctype字符串转换为数字。对于单个字符,应使用算术或查找表进行此转换。

此外,没有必要将字符转换为整数然后将其打印(返回字符)。你应该更好地打印数字字符。

此外,在C ++中,我更喜欢使用stringstream而不是atoi。在C ++ 11上,还有更高级的解决方案,比如sto *。