c++ - Linux 中的结果与 Windows C++ 中的结果不同

标签 c++ linux

我已经在 Microsoft Visual Studio Express 2013 中创建了代码,它可以正常编译和运行。我已将其移至 Linux,它为我提供了不同的 GPA 输出结果。 GPA 为 0 和 6.95281e-310,而不是 3.9 和 3.5。

还想知道 strcmp 之间是否有区别和strncpy在 Linux 中,因为我必须添加 #include <cstring>在我的学生.h 中?

我应该使用其他东西来代替 strncpy在 Linux 中?

学生.h

#ifndef STUDENT_H
#define STUDENT_H

#include <iostream>
#include <cstring>
using namespace std;

class Student
{
public:
    Student(const char initId[], double gpa);
    bool isLessThanByID(const Student& aStudent) const;
    bool isLessThanByGpa(const Student& aStudent) const;
    void print()const;
private:
    const static int MAX_CHAR = 100;
    char    id[MAX_CHAR];
    double  gpa;
};
#endif

学生.cpp

#include "student.h"


//implement the required 3 functions here


Student::Student(const char initId[], double gpa) : gpa(gpa)
{
    // initialize a newly created student object with the passed in value
    strncpy(id, initId, Student::MAX_CHAR - 1);
    if (Student::MAX_CHAR > 0)
{
    id[Student::MAX_CHAR - 1] = '\0';
}


}

bool Student::isLessThanByID(const Student& aStudent) const
{
    //  compare the current student object with the passed in one by id.
    if (strcmp(id, aStudent.id) > 0)
    {
        return true;
    }
    else
    {
        return false;
    }


}

bool Student::isLessThanByGpa(const Student& aStudent) const
{
    // compare the current student object with the passed in one by gpa
    if (gpa < aStudent.gpa)
    {
        return true;
    }
    else
    {
        return false;
    }

}

void Student::print() const
{
    cout << id << '\t' << gpa << endl;
}

应用程序.cpp

#include "student.h"

int main()
{
    Student s1("G10", 3.9);
    Student s2("G20", 3.5);

    s1.print();
    s2.print();

    if(s1.isLessThanByID(s2))
    {
        cout << "about right!" << endl;
    }
    else
    {
        cout << "uhmm ..." << endl;
    }
    if(!s1.isLessThanByGpa(s2))
    {
        cout << "about right!" << endl;
    }
    else
    {
        cout << "uhmm ..." << endl;
    }

    //system("pause");
    return 0;
}

最佳答案

strcmp 比较字符串 http://www.cplusplus.com/reference/cstring/strcmp/

strncpy 复制它们 http://www.cplusplus.com/reference/cstring/strncpy/

它们之间确实存在很大的差异,在 Linux 和其他系统中也是如此。

关于c++ - Linux 中的结果与 Windows C++ 中的结果不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33201476/

相关文章:

c++ - 如何获得 "bus error"?

linux - shell 脚本。我的脚本中的命令替换问题

linux - 尝试使用随机结尾的 grep url

python - Django 在 Linux 中找不到我的模型,但在 Windows 中可以

linux - 使用 -C(或 -B/-A)运行时在 grep 结果之间输出空行

linux - 如果在一台 x86 主机上运行 2 个 type-2 VMX hypervisor 会怎样?

c++ - 从 MSI 获取模块文件名

c++ - STL,减少数组,C++

c++ - 模板类类型调整

C++:如何在类被模板化时使用默认构造函数实例化后将输入输入到对象中