c++ - 在 C++ 中将字符串转换为整数而不丢失前导零

标签 c++

你好,我在将一串数字转换为整数时遇到了问题。 问题是使用 atoi() 将字符串转换为整数我丢失了前导零。 你能告诉我一种不丢失前导零的方法吗?

#include <fstream>
#include <iostream>
#include <iomanip>
#include <string>


using namespace std;

struct Book{
    int id;
    string title;
};

struct Author{
    string firstName; 
    string lastName;
};

Author authorInfo[200];
Book bookInfo[200];

void load ( void )
{

    int count = 0;
    string temp;

    ifstream fin;
    fin.open("myfile.txt");

    if (!fin.is_open())
    {
        cout << "Unable to open myfile.txt file\n";
        exit(1);
    }

    while (fin.good())
    {   
        getline(fin, temp, '#');
        bookInfo[count].id = atoi(temp.c_str());
        getline(fin, bookInfo[count].title, '#');
        getline(fin, authorInfo[count].firstName, '#');
        getline(fin, authorInfo[count].lastName, '#');
        count++;
    }

    fin.close(); 
}

最佳答案

好的,所以我认为您实际上并不想存储前导零。我认为您想在输出中显示一致数量的数字。

因此,例如,要显示 5 位数字的固定大小的 ID [请注意,100000 的 id 仍将以 6 位数字显示 - 它在这里所做的只是确保它始终至少为 5数字,如果数字不够大,用'0'填充],我们可以这样做:

std::cout << std::setw(5) << std::setfill('0') << id << ... 

或者,如其他答案中所建议的,您不想以整数形式使用 ID,您可以将其存储为字符串 - 除非您要对其进行数学运算,否则它就是这样变化是每本书占用的内存稍微多一点。

关于c++ - 在 C++ 中将字符串转换为整数而不丢失前导零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17332767/

相关文章:

c++ - 继承抽象基接口(interface)及其实现给出 C2259

c++ - 交换功能中的段错误

c++ - 头文件中的类 - 无法编译?

c++ - 我可以执行 gzseek 来更新使用 gzwrite (CPP) 压缩的文件吗?

java - 在Java中使用C++模板框架

c++ - 有没有更好的方法来反转循环中的 bool 值?

c++ - 如何获取指向引用成员的指针?

c++ - 最短路径加权矩阵

c++ - 编写程序以便为 if 语句分配适当的编号

C++解析,从字符串中获取可变数量的整数