字符串超出范围

Out of range string?

本文关键字:范围 字符串      更新时间:2023-10-16

嘿,伙计们,我得到了一个字符串.at(x)的超出范围的错误,我不知道为什么。任何帮助,基本上我都在努力确保第一个字符不是<'对象字符串中的'or>'z'。此外,我认为我的字符串比较可能无法正常工作,但如果我发现有重复的唯一单词,这可能更多地与未完成的代码有关。

struct wordCount{
string word;
int count;
}storeword[100];
void countWordFreq(wordCount compares[]){
int a=0;
unsigned i=0;
for(a;a<101;a++){
    cout<<"Length"<<compares[a].word.length();
    if(compares[a].word.at(i)<='z'||compares[a].word.at(i)>='A'){       
    compares[a].count++;
    }
    for(int b=1;b<101;b++){
        cout<<"Length"<<compares[b].word.length();
        if(compares[b].word.at(i)<='z'||compares[b].word.at(i)>='A'){           
        if(compares[a].word.compare(compares[b].word)==0){
            cout<<"true" << endl;
            compares[a].count++;
        }
    }
        b++;
    }
    a++;
}
for(int q;/*compare[q].word.at(0)<='z'||compare[q].word.at(0)>='A'*/q<10;q++){
    cout<<"Word: " << compares[q].word << " Count: " << compares[q].count << endl;
}

}

哇。冒着听起来(不礼貌)的风险,我想我会以完全不同的方式做这项工作。

C++标准库提供了相当多的工具,可以更容易地完成这项工作,而很难发现错误等的几率要小得多。我会使用它们。

值得一提的是:我不确定我是否完全理解你对每个单词的第一个字符所描述的比较。目前,我假设你只想数以字母开头的东西。不过,如果需要的话,改变这一点很容易。

#include <string>
#include <map>
#include <iostream>
#include <iomanip>
#include <cctype>
#include <sstream>
void countWordFreq(std::string const &input) {
    std::map<std::string, size_t> counts;
    std::istringstream buffer(input);
    std::string word;
    // read the words, count frequencies of those that start with letters
    while (buffer >> word)
        if (isalpha(word[0]))
            ++counts[word];
    // write out each word we found and how often it occurred:
    for (auto const &count : counts)
        std::cout << std::setw(20) << count.first << ": " << count.second << "n";
}

目前,这将按字母顺序打印出独特的单词。如果您不需要订购,您可以(通常)使用std::unordered_map而不是std::map来提高速度。