-3

我目前对为什么我的程序没有按应有的方式执行感到困惑。每当我运行它时,它只执行第一个 cout & cin 语句并完全绕过第二个语句。程序需要请求两个名称并将它们存储在字符串对象中。

然后它应该报告它们是否相同,忽略大小写(如测试名称“jack”是否与“JACK”相同,它将显示名称相同,忽略小写/大写字母的差异.) 该问题提供了程序所需的两个标头,因此您将在初学者中看到 bool 和 string 标头。

这是我当前的代码: http: //pastebin.com/Ju0MjkfP

#include <iostream>
using namespace std;

string upperCaseIt(string s);
bool sameString (string s1, string s2);

int main ()
{
    char name1, name2;

    cout << "Enter a name: ";
    cin >> name1;

    cout << "Enter another name and I will test if they are the same.";
    cin >> name2;

    if (name1==name2)
       cout << name1 << " is the same as " << name2 << endl;

    if (name1!=name2)
        cout << name1 << " is not the same as " << name2 << endl;

    system ("pause");
    return 0;
}
bool sameString (char name1)
{
     if (name1)
        return true;
     else
         return false;
}

编辑:我输入了“jack”和“JACK”来测试它。

任何提示将不胜感激;谢谢。

4

3 回答 3

3

当你声明

char name1, name2;

您声明了两个单字符变量。如果你想要一个字符串,你应该使用std::string

std::string name1, name2;
于 2013-11-10T18:46:19.627 回答
3

你应该使用std::string,而不是char。一个char变量只能包含一个字符(例如,一个'a',但不是像“Alfred”这样的全名。

所以你应该做

std::string name1, name2;

代替

char name1, name2;

此外,您sameString似乎还不完整,它仅检查您的name1变量是否为 != 0

于 2013-11-10T18:46:44.440 回答
2

To elaborate on the other correct answers, the reason it "skips" the second cin is that input is buffered. When it asks you for a name, you type several characters (e.g., Mike). The following line calls the operator>> method on cin to store the data you entered. If you had declared name1 as a std::string, it would read up to the newline character, save the string "Mike" in the variable, and discard the newline. At that point, every character you typed will have been read in, so nothing is left in the buffer.

However, you declared name1 as a char -- a single character. So when C++ does the cin >> name1 call, it rightly realizes that it can only store one letter, so that's all it reads. That means name1 is just 'M', and there's still stuff left that hasn't been read yet. In this case, "ike". So the next time it needs to read sometime, it doesn't need to wait on you to type anything else. It just continues reading from the buffer you've already filled.

于 2013-11-10T18:52:34.663 回答