返回 Alt 代码而不是 int C++

Alt code being returned instead of int C++

本文关键字:int C++ Alt 代码 返回      更新时间:2023-10-16

我目前正在为一个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
最上面的数字是总统编号,第二个是他们的名字,第三个是他们的出生日期和死亡日期,4个是

他们就职的日期,5个是他们离任的时间,6个是政党,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,即 ♥ .任何帮助,不胜感激。

如果没有看到输出代码,就会发生这种情况的原因有很多。但最有可能的是,你正在发生这样的事情:

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任总统的事实,只是一个例子)。

例子

之前: http://cpp.sh/2tjj

之后:http://cpp.sh/8izy