C++ 输入多个字符串C++;
下面的代码尝试输入多个带空格的字符串,然后我需要对它们进行比较。我面临的问题是,它无法输入超出第一个字符串的字符串。我认为是输入缓冲区中剩余的“enter”导致了这种行为,即跳过字符串的进一步输入。有什么建议可以克服这个问题吗 参考: 已编辑:清除和刷新我已尝试过,但仍然是同一问题。 我需要实现C风格的字符串函数,所以不能使用字符串类,strcmp等函数必须由我来实现,而不是使用库函数C++ 输入多个字符串C++;,c++,string,C++,String,下面的代码尝试输入多个带空格的字符串,然后我需要对它们进行比较。我面临的问题是,它无法输入超出第一个字符串的字符串。我认为是输入缓冲区中剩余的“enter”导致了这种行为,即跳过字符串的进一步输入。有什么建议可以克服这个问题吗 参考: 已编辑:清除和刷新我已尝试过,但仍然是同一问题。 我需要实现C风格的字符串函数,所以不能使用字符串类,strcmp等函数必须由我来实现,而不是使用库函数 int main() { char s[100]; char s1[1
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;
}
#包括
#包括
使用名称空间std;
int main()
{
字符串s1=“”;
字符串s2=“”;
coutstd::cin.ignore(100,“\n”);
成功了。仅通过搜索[c++]cin buffer
或[c++]CIN跳过 .SO 1,不做任何研究工作。也考虑使用<代码> STD::String < /Cord>代替C字符串,可能存在缓冲区溢出问题。@ RAPTZ I已经尝试刷新输入流(刷新和清除)但是我还是不明白你的投票,我也必须手动实现C型字符串函数,这就是为什么不使用C++字符串的原因。解决方案将被取代而不是投票。这会是什么样的?在发布之前你试着运行它吗?我不需要使用String类,我需要实现空终止STR。如果您添加注释来解释您的代码行的功能,将非常有帮助。
$ ./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
#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;
}