我得到了與該代碼的問題:垃圾在焦炭
golf.h:
const int Len = 40;
struct golf
{
char fullname[Len];
int handicap;
};
void setgolf(golf & g, const char * name, int hc);
void setgolf(golf & g);
void handicap(golf & g, int hc);
void showgolf(const golf & g);
golf.cpp:
#include <iostream>
#include "golf.h"
using namespace std;
void setgolf(golf & g, const char * name, int hc)
{
int i=0;
while(*name != '\0')
{
g.fullname[i] = name[0];
cout << "g.fullname[i]: " << g.fullname[i] << ", name[0]: " << name[0] << endl;
name++;
i++;
}
g.handicap = hc;
cout << "setgolf: " << g.fullname << ", " << g.handicap << endl;
}
void setgolf(golf & g)
{
}
void showgolf(const golf &g)
{
cout << "showgolf: " << g.fullname << ", " << g.handicap << endl;
}
main.cpp中:
#include <QCoreApplication>
#include <iostream>
#include "golf.h"
using namespace std;
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
golf selby, higgins, sullivan;
setgolf(selby, "Mark Selby", 10);
setgolf(higgins, "John Higgins", 20);
setgolf(sullivan, "Ronnie O'Sullivan", 30);
showgolf(selby);
showgolf(higgins);
showgolf(sullivan);
return a.exec();
}
問題是.....當我在調試模式下運行時,我得到了結果:
showgolf: Mark Selby, 10
showgolf: John [email protected], 20
showgolf: Ronnie O'Sullivanvr, 30
只需1日進入到setgolf()和showgolf是正確的,在休息時增加字符的結束一些垃圾...
但是,當我在Release模式下運行,我得到不同勢的結果:
showgolf: Mark Selby,ujs,uČjć'ł, 10
showgolf: John Higgins■ js,[email protected], 20
showgolf: Ronnie O'Sullivan, 30
最後一個輸入到setgolf()和showgolf()是正確的,在休息時也添加了一些垃圾。
有人可以解釋我爲什麼垃圾是他們從哪裏來的?
當你到達名字的末尾時,在'void setgolf(golf&g,const char * name,int hc)'中,你必須將'fullname'的剩餘字符設置爲零。 – navyblue
使用std :: string而不是char數組。而且由於你使用Qt,你也可以使用QString。 – 2017-10-21 17:43:49
那些是斯諾克球員,而不是高爾夫球。 –