如何使用strcmp()比较包含空格的两个字符串?
带空格字符串输入后跳过第二个输入的解决方法
问题重现
原代码如下:
#include <iostream> #include <cstring> #include <cctype> using namespace std; int main(){ char string1 [50] {}; char string2 [50] {}; cout << "enter the string 1: "; cin.get(string1,50); cout << "your string1: " << string1 << endl; cout << "enter the string 2: "; cin.get(string2,50); cout << "your string2: " << string2 << endl; cout << strcmp(string1, string2); return 0; }
输入abc def后,程序直接跳过第二个字符串的输入步骤,输出如下:
your string1: abc def enter the string 2: your string2: 1
无法正常比较两个带空格的字符串,期望输入相同带空格字符串时strcmp返回0。
问题原因
cin.get(char*, n)会读取字符直到遇到换行符或达到指定长度,但不会将换行符从输入缓冲区中移除。当第二个cin.get执行时,会直接读取到缓冲区中残留的换行符,判定输入结束,导致string2为空。
解决方法
在第一个cin.get之后,添加代码跳过输入缓冲区中的换行符。有两种常用方式:
- 简单跳过单个换行符:
cin.ignore();
- 更稳妥的方式,跳过缓冲区中所有直到换行的字符(避免缓冲区有多余字符的情况),需要包含
<limits>头文件:
#include <limits> // ... cin.ignore(numeric_limits<streamsize>::max(), '\n');
修改后的完整代码
#include <iostream> #include <cstring> #include <cctype> #include <limits> using namespace std; int main(){ char string1 [50] {}; char string2 [50] {}; cout << "enter the string 1: "; cin.get(string1,50); cout << "your string1: " << string1 << endl; // 跳过输入缓冲区中残留的换行符 cin.ignore(numeric_limits<streamsize>::max(), '\n'); cout << "enter the string 2: "; cin.get(string2,50); cout << "your string2: " << string2 << endl; cout << strcmp(string1, string2); return 0; }
测试效果
两次输入abc def,程序会正常读取两个字符串,strcmp返回0,符合预期。
内容的提问来源于stack exchange,提问作者Pandaa
相关产品推荐
相关产品推荐

