我已经在 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/