下面的代码尝试输入带有空格的多个字符串,然后我需要在它们之间进行比较。我面临的问题是,它无法输入超出第一个字符串的字符串。我认为输入缓冲区中剩余的'enter'导致这种行为,即跳过进一步的字符串输入。有什么建议如何克服这个?
编辑:清除和清除我尝试但仍然是同样的问题。 我需要实现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
答案 0 :(得分: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;
}
答案 1 :(得分:-1)
std::cin.ignore(100,'\n');
成功了。