我目前正在开发一个C ++类的项目,分配如下。 创建一个程序,读取总统文件,并要求用户猜测所选总统的正确值。 我们得到了一个包含所有数据的.txt文件,并且在文件中就是这样。
1
George Washington
(1732 to 1799)
April 30, 1789
March 4, 1797
Independent
Commander-in-Chief; of the Continental Army (1775 to 1783)
John Adams
2
John Adams
(1735 to 1826)
March 4, 1797
March 4, 1801
Federalist
Vice President
Thomas Jefferson
最高号码是总统号码,第二个是他们的姓名,第三个是他们的出生日期和死亡日期,第四个是他们上任的那天,第五个是他们离开办公室,第六个是派对,第七个是以前的办公室,以及7日是他们的副总统。这是读取文件的方法的代码。
void presidentGame::readPresidents(){
string fileName = "presidents.txt";
string strNum, name, birthDeath, tookOffice, leaveOffice, party, previousOffice, vicePresident;
int num;
ifstream inFile(fileName);
if (! inFile) {
cout << "Failed to find the file " << fileName << endl;
}
else {
while (getline(inFile, strNum)){
num = stoi(strNum); //I did this because an actual int is better than a string
getline(inFile, name);
getline(inFile, birthDeath);
getline(inFile, tookOffice);
getline(inFile, leaveOffice);
getline(inFile, party);
getline(inFile, previousOffice);
getline(inFile, vicePresident);
president tempPresident(num, name, birthDeath,tookOffice, leaveOffice, party, previousOffice, vicePresident);
presidents.push_back(tempPresident);
}
}
}
正在发生的问题是num在命令提示符下显示为Alt代码值。以下是正确回答时的输出示例。
***********************************************
Correct Incorrect Total Guesses
======= ========= =============
0 11 11
Guess which President Thomas Jefferson was? <♥> 3
Congrats, You finally got one right!
Thomas Jefferson was the ♥rd President
President Information:
============================
He lived from (1743 to 1826)
He took office March 4, 1801
He left office on March 4, 1809
His party was Democratic-Republican
His previous office held was Vice PresidentHis vice president was 1st term: Aaro
n Burr / 2nd term: George Clinton
Press any key to continue...
因此,不是将数字显示为“3”,而是将其显示在alt + NUM_3,即♥。任何帮助表示赞赏。
答案 0 :(得分:2)
如果没有看到输出代码,可能会出现多种原因。但最有可能的是,你有这样的事情发生了:
string outputBuffer = presidentName;
outputBuffer += " was the ";
outputBuffer += presidentNumber; // The problem is here.
outputBuffer += getSuffix(presidentNumber); // Or whatever logic you have for this
outputBuffer += " President";
修复很简单:
outputBuffer = to_string(presidentNumber); // Replace the problem line with this
C ++在类型检测方面相当不错,但它仍然是一种强类型语言。编译器将presidentNumber
解释为文字字符并且没有错误(尽管取决于您的编译器和标志,您可能会收到警告)。
因此,如果presidentNumber = 65
,则表示“A”字符。 (别担心没有第65任总统,只是一个例子)。
<强>实施例强>