C++特殊字符串单词统计程序技术错误排查及修正请求
Fixing Your Word Counting Code (C++)
Hey there! Let's break down why your current code is returning 0 instead of the expected 6, and fix it using the same basic syntax you're already using so it's easy to follow.
Key Issues in Your Original Code
- Array Out-of-Bounds Error: When
i = 0, you try to accessstr[i-1](which isstr[-1]). This is illegal in C++—it's undefined behavior that can crash your program or mess up your logic, which is a big reason you're getting 0. - Overly Complicated & Incorrect Counting Logic: Your conditions for counting words are tangled. You're trying to use spaces to trigger counts, but you didn't account for the first word (which has no leading space) and your conditional checks don't correctly identify when a new word starts.
Corrected Code
#include <iostream> using namespace std; int main() { string str = " Let's count the number of words "; int word = 0; bool inWord = false; // Tracks if we're currently inside a word for (int i = 0; str[i] != '\0'; ++i) { // We found the start of a new word if (str[i] != 32 && !inWord) { word++; inWord = true; // Mark that we're now inside a word } // We found the end of a word else if (str[i] == 32 && inWord) { inWord = false; // Mark that we've left the word } // Do nothing for consecutive spaces or consecutive word characters } cout << "No. of words: " << word << endl; return 0; }
How This Works
- No More Out-of-Bounds Access: Instead of checking
str[i-1], we use a simple boolean flaginWordto track our current state (inside a word or not). This avoids all risky invalid array accesses. - Clear Counting Logic:
- When we hit a non-space character and we weren't in a word before, that's the start of a new word—so we increment
wordand setinWordtotrue. - When we hit a space and we were in a word before, that's the end of the current word—so we set
inWordtofalse. - Consecutive spaces or consecutive word characters don't trigger any changes, which handles leading/trailing spaces and multiple spaces between words perfectly.
- When we hit a non-space character and we weren't in a word before, that's the start of a new word—so we increment
This code will correctly return 6 for your test string, 2 for " Hello world ", and 5 for "Hello world! How are you? "—all as expected.
内容的提问来源于stack exchange,提问作者Harish
相关产品推荐
相关产品推荐

