-3

下面的代码尝试输入多个带有空格的字符串,然后我需要在它们之间进行比较。我面临的问题是,它无法输入第一个字符串以外的字符串。我想是输入缓冲区中剩余的“输入”导致了这种行为,即跳过字符串的进一步输入。任何建议如何克服这个问题?

参考:如何在 c++ 中 cin 空间?

编辑:清除和冲洗我试过但仍然是同样的问题。我需要实现C风格的字符串函数,所以不能使用字符串类,函数strcmp等必须由我实现而不是使用库函数。

int main()
    {
        char s[100];
        char s1[100];
        char s2[100];
        char* sub;

        struct countSpaces cs;



cout << "Enter a String : ";
cin.get( s, 100 );
std::cin.clear();
cs=count(s);

cout << s << " contains " << cs.letters << " letters and " << cs.spaces << " spaces" << endl;
cout << "Length of " << s << " is " << strlen(s) << endl;

cout << "Enter First String : ";
cin.get( s1, 100 );
std::cin.clear();
cout << "Enter second String : ";
cin.get( s2, 100 );
std::cin.clear();

        if( strcmp(s1,s2) )
        cout << s1 << " is equal to " << s2 << endl;
        else
        cout << s1 << " is not equal to " << s2 << endl;


        return 0;
        }

输出:

$ ./String
Enter a String : Herbert Schildt
Herbert Schildt contains 14 letters and 1 spaces
Length of Herbert Schildt is 15
Enter First String : Enter second String :  is not equal to
4

2 回答 2

0
#include <iostream>
#include <string>

using namespace std;

int main()
{
    string s1 = "";
    string s2 = "";

    cout << "Enter first string > ";

    getline(cin, s1);

    cout << "Enter second string > ";

    getline(cin, s2);

    if(strcmp(s1,s2))
        cout << s1 << " is equal to " << s2 << endl;
    else
        cout << s1 << " is not equal to " << s2 << endl;

    // copy string s1 into C-String str
    char * str = new char [s1.length()+1];
    std::strcpy (str, s1.c_str());

    return 0;
}
于 2013-04-16T06:15:17.927 回答
-1

std::cin.ignore(100,'\n');成功了。

于 2013-04-16T06:24:26.813 回答