你好,我在将一串数字转换为整数时遇到了问题。 问题是使用 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/