字符数组提取所有字符串:首尾空格导致结果异常的修复方案求助
从char数组提取单词的问题修复需求
我折腾了一整天都没搞定这个问题:要从输入的char数组里提取并打印所有单词,但输入首尾有空格时结果就出错。求易懂的修复方案或思路,允许用容易理解的库。
附当前C++代码:
#include <iostream> #include <ctype.h> #include <stdio.h> #include <cmath> #include <string> #include <stdlib.h> #include <sstream> using namespace std; const int len = 1000; char inputnames[len]; int main() { int counter = 0, z = 0; cout << "Type in the Candidates names and press enter please: "; cin.getline(inputnames, len); string stringstream(inputnames); string token; char LastCharacter = stringstream.back(); if (LastCharacter == ' ') { counter = 0; for (int z = 0; z < len; z++) { if (inputnames[z] >= 'a' && inputnames[z] <= 'z' && inputnames[z + 1] == ' ' || inputnames[z] >= 'A' && inputnames[z] <= 'Z' && inputnames[z] == ' ') { counter++; } cout << inputnames[z]; } } else if (LastCharacter != ' ') { counter = 1; for (int z = 0; z < len; z++) { if (inputnames[z] >= 'a' && inputnames[z] <= 'z' && inputnames[z + 1] == ' ' || inputnames[z] >= 'A' && inputnames[z] <= 'Z' && inputnames[z] == ' ') { counter++; } cout << inputnames[z]; } } }
另外我已经修复了输入末尾空格导致计数多1的bug,欢迎提供更多建议、帮助或批评。
修复方案与优化思路
核心问题分析
你当前的代码逻辑绕了弯路:直接操作char数组的空格判断条件混乱,还遍历了整个固定长度数组(会打印未初始化的垃圾字符),而且stringstream变量名和标准库重名,存在命名冲突风险。
方案1:用标准库istringstream(最简单可靠)
istringstream会自动忽略首尾及中间的连续空格,完美适配需求,代码简洁易懂:
#include <iostream> #include <string> #include <sstream> using namespace std; int main() { char inputnames[1000]; cout << "Type in the Candidates names and press enter please: "; cin.getline(inputnames, 1000); string input_str(inputnames); istringstream iss(input_str); string word; int word_count = 0; // 自动跳过空格,逐个提取单词 while (iss >> word) { cout << word << endl; // 按需调整打印格式 word_count++; } cout << "总单词数:" << word_count << endl; return 0; }
方案2:手动实现逻辑(适合理解底层原理)
如果想手动处理char数组,核心逻辑是先跳过开头空格,读取单词时判断字符是否为空格,结束单词后跳过后续连续空格:
#include <iostream> #include <cctype> // 用isspace判断所有空白字符,更通用 using namespace std; const int len = 1000; char inputnames[len]; int main() { cout << "Type in the Candidates names and press enter please: "; cin.getline(inputnames, len); int i = 0; int word_count = 0; while (inputnames[i] != '\0') { // 遍历到字符串结束符为止 // 跳过开头的所有空格 while (isspace(inputnames[i]) && inputnames[i] != '\0') { i++; } // 读取当前单词 if (inputnames[i] != '\0') { word_count++; cout << "单词" << word_count << ": "; while (!isspace(inputnames[i]) && inputnames[i] != '\0') { cout << inputnames[i]; i++; } cout << endl; } } cout << "总单词数:" << word_count << endl; return 0; }
对你现有代码的批评与建议
- 命名冲突:变量名
stringstream和标准库的std::stringstream重名,会导致编译错误或逻辑混乱,必须改名。 - 无效遍历:遍历固定长度
len的数组,会打印输入字符串之后的未初始化垃圾字符,应该只遍历到字符串结束符'\0'。 - 逻辑错误:
inputnames[z] >= 'A' && inputnames[z] <= 'Z' && inputnames[z] == ' '这个条件永远为假,一个字符不可能既是字母又是空格。 - 冗余操作:没必要同时操作char数组和string,选一种即可,string的操作更安全便捷。
内容的提问来源于stack exchange,提问作者user19729408
相关产品推荐
相关产品推荐

