C++字符串解析代码输出first字段后多额外空格如何排查修复?
问题定位
- 你使用
getline(stream, first, ',')读取逗号前的内容时,该函数会保留逗号前的所有字符,包括逗号前面的尾随空格,这些空格会被存入first变量,输出时就会显示额外的空格。 - 举个例子:如果输入内容为
test , example,那么读取到的first值为test(末尾带空格),输出时自然会多一个空格。
修复方案
只需要在读取到first变量后,添加去除尾部空白的逻辑即可,修改后的完整代码如下:
#include <iostream> #include <string> #include <sstream> #include <cctype> // 新增头文件,用于判断空白字符 using namespace std; int main() { string userStr; bool inputDone = false; while(!inputDone) { bool commaCheck = false; do { cout << "Enter input string:" << endl; getline(cin, userStr); if (userStr == "q") { inputDone = true; break; } else{ for (unsigned int i = 0; i < userStr.length(); i++) { if (userStr[i] == ',') commaCheck = true; } if (!commaCheck) { cout << "Error: No comma in string." << endl << endl; } } } while (!commaCheck); if(!inputDone) { string first, second; istringstream stream(userStr); getline(stream, first, ','); // 新增:去除first尾部的所有空白字符 while (!first.empty() && isspace(static_cast<unsigned char>(first.back()))) { first.pop_back(); } stream >> second; cout << "First word: " << first << endl; cout << "Second word: " << second << endl; cout << endl; } } return 0; }
补充说明
- 如果你需要同时去除
first开头的多余空格,可以在去除尾部空白前再加一段处理开头的逻辑:
// 去除开头空白 size_t start = first.find_first_not_of(" \t"); if (start != string::npos) { first = first.substr(start); } else { first.clear(); }
内容的提问来源于stack exchange,提问作者Keightlyn Thornton
相关产品推荐
相关产品推荐

