GCC环境下使用fgets读取输入时移除末尾换行符的实现方法
GCC环境下移除fgets输入自带的尾部换行符
在GCC环境中使用fgets函数读取标准输入时,函数会将用户输入末尾的换行符一同存入目标字符串中,若后续需要对字符串做比对等操作,需要先将这个多余的换行符移除。
原始测试代码
#include <iostream> #include <cstring> using namespace std; int main() { char x[10]; fgets(x,10,stdin); cout << x << endl; return 0; }
实现方案
使用strcspn函数可以高效定位换行符位置,无需手动遍历字符串:strcspn函数会返回输入字符串中第一个匹配目标字符集中任意字符的下标,我们找到\n的位置后,直接将该位置赋值为字符串结束符\0(等价于写0)即可完成换行符移除。
可行实现代码
#include <iostream> #include <string> #include <cstring> using namespace std; int main() { char x[20]; fgets(x,sizeof(x),stdin); // 移除尾部换行符 x[strcspn(x,"\n")] = 0; cout << x << endl; // 测试字符串比对逻辑 if(!strcmp(x,"hello world!")) { cout << "yes" << endl; } return 0; }
内容的提问来源于stack exchange,提问作者pascal111
相关产品推荐
相关产品推荐

