如何在C ++中有效地使用字符串data_type?

时间:2012-02-09 16:05:19

标签: c++ string

我尝试制作这个小程序,接受输入并检查元音。如果有元音,则将它们附加到字符串并返回字符串的大小。

我唯一的问题是我无法使用字符串工作。使用字符数组的主要区别是什么?我可以使用类似的东西让程序工作:

char entered[128];
//and then
char exceptions[11] = "aeiouAEIOU";

**关于上述数组的快速问题。当我将缓冲区分配给“exception”时,它必须是11或编译器将出错。我必须手动考虑NULL终止部分吗?

如果我这样做:

if(cPtrI[i] == 'a'){

我收到错误,说明未知运算符'=='?? 我以为'=='是一个检查运算符,'='是一个赋值运算符?

no match for 'operator==' in '*((+(((unsigned int)i) * 4u)) + cPtrI) == 'a''|

并且,如果我做了类似的事情(我认为最初是正确的)

if(*cPtrI[i] == *cPtrJ[j]){

我得到与上面相同的错误,但引用了未知的运算符*:

no match for 'operator*' in '**((+(((unsigned int)i) * 4u)) + cPtrI)'|
no match for 'operator*' in '**((+(((unsigned int)j) * 4u)) + cPtrJ)'|

我认为*运算符实际上是说'指针指向的地址是什么'。

所以,像上面这样的东西会读到:

If(What is at index I of string 'a' EQUALS What is at index J of string 'exceptions'){
then ..

对此有何帮助?我在C ++之前学过C,所以也许这就是我的困惑所在。据我所知,上面的代码会比较它们指向的字符/变量的地址。 *表示'what at',而只是放置指针名称将指示指针所持有的值(这是指向的变量的地址)。使用& ptrName将是指针本身的地址,对吗?我在哪里错了?

#include <iostream>
#include <string>

int vowelCheck(std::string a);

int main()
{using namespace std;

    string eString;
    cout << "Enter a string: ";
        cin >> eString;
    cout << "There were " << vowelCheck(eString) << " vowels in that string.";
    return 0;
}

int vowelCheck(std::string a)
{using namespace std;

    string exceptions = "aeiouAEIOU";
    string vowels;
    string *cPtrI = &a;
    string *cPtrJ = &exceptions;

    for(int i = 0; i < a.size(); i++){
        cout << i <<"i\n";
        for(int j = 0; j < 10; j++){
            cout << j << "j\n";
           // cout << cPtrJ[j];
            if(cPtrI[i] == cPtrJ[j]){ //if index of A equal index of J then
                cout << "Added: " << cPtrJ[j];
                vowels.append(cPtrJ[j]); // append that vowel to the string 'vowels'
                break;
            }
        }
    }
    return vowels.size();
}

使用上面列出的调试工具,程序只会增加j = 8然后停止。此外,如果我甚至输入类似AEIOU的初始字符串,它将通过j = 8字符串。因此,它没有看到等效的字符。

使用字符串我做错了什么?

3 个答案:

答案 0 :(得分:4)

忘掉指针

string *cPtrI = &a;
string *cPtrJ = &exceptions;

// ...

if(cPtrI[i] == cPtrJ[j]){ //if index of A equal index of J then

cPtrI[i]*(cPtrI + i)相同,后者将编入string数组。

这就是cPtrI[i] == 'a'无法编译的原因。 cPtrI[i]的类型为std::string&(请记住,它正在索引到不存在的std::string数组中),'a'char。你无法比较两者。

std::string有自己的索引运算符。只是不要使用无意义的指针,它只是工作

if(a[i] == exceptions[j]){

答案 1 :(得分:4)

您似乎在计算字符串中的元音数量。不要手动写出for循环并构建字符串,让我们使用count_if来做到这一点。计划是创建一个函数对象,可以检测字符是否是元音,然后使用count_if来计算字符串中元音字符的数量:

struct VowelFinder
{
    bool operator()(char c)
    {
        std::string vowels = "aeiouAEIOU";
        return vowels.find(c) != std::string::npos;
    }
};

int vowelCheck(const std::string& a)
{
    return std::count_if(a.begin(), a.end(), VowelFinder());
}

答案 2 :(得分:3)

我在评论中回答了你的C相关问题。

至于您对std::string的使用情况,您实际上是出于某种原因尝试使用std::string*。不要那样做。只需使用std::string;运算符[]已超载,因此无法按原样运行。目前,您将cPtrI视为字符串数组的元素。