【问题标题】:getline truncating first charactergetline截断第一个字符
【发布时间】:2015-12-02 06:49:57
【问题描述】:

我已经看过hereherehere。我没有使用 cin.ignore()。这段代码有两个问题,但会限制为一个。 unsigned int int long "sID" 应该包含 "020961797" 但只包含 "20961797"。

bool GPA::importStudents(string mapFileName, string setFileName)
{
long long int sID;
string sName;
string sAddress;
string sPhone;
stringstream ss;

string line;
int mline_count = 0;
int sline_count = 0;
double x;
int y;
ifstream map_file;
ifstream set_file;
map_file.open(mapFileName);
set_file.open(setFileName);

    if (map_file.is_open()){
    for (int i = 0; i < mline_count/4; i++){
        getline(map_file, line);
        ss << line;
        ss >> sID;

        getline(map_file, line);
        ss << line;
        ss >> sName;

        getline(map_file, line);
        ss << line;
        ss >> sAddress;

        getline(map_file, line);
        ss << line;
        ss >> sPhone;

        StudentInterface * SI = new Student(sID, sName, sAddress, sPhone);
        my_map.insert(std::pair<unsigned long long int, StudentInterface*>(sID, SI));

        //my_map.emplace(Student(sID, sName, sAddress, sPhone));
    }
}
}

这是它应该从中读取数据的文件的第一部分:

020961797

约书亚·库珀

0509 McCrooke Avenue, Columbus, California 52826

552-534-8671

【问题讨论】:

标签: c++


【解决方案1】:

sID 实际上包含1001111111101101000000101b,因为它有一个数字表示。使用默认格式打印,它确实呈现为20961797。如果需要,可以通过操纵器 setw(9)setfill(' ') 强制前导 0 获取 020961797

除非您必须对该字段值执行算术运算,否则将其作为字符串处理可能更合适。

【讨论】:

    【解决方案2】:

    您不能使用int 来存储前导零,您必须将sID 存储为string,然后在必要时将其转换为数字。可以说,ID 是标识符而不是数字,您实际上不需要对其进行任何数学运算,因此string 将是一个理想的解决方案

    string sID = "020961797";
    
    //For some reason you need the ID as a number
    int idToInt = atoi(sID.c_str());
    

    请注意,int 在转换时不会保留前导零

    【讨论】:

      【解决方案3】:

      数值类型保存数字,而不是数字的表示。 “十”、“10”、“010”、“我的手指数”、“IIIIIIIII”都是同一个数字的不同表示。如果要保存字符,请使用字符串。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-04-12
        相关资源
        最近更新 更多