[英]How do effectively use the string data_type in C++?
我尝试制作这个小程序,接受输入并检查元音。 如果有元音,则将其附加到字符串中并返回字符串的大小。
我唯一的问题是我无法使用字符串来使其正常工作。 使用字符数组的主要区别是什么? 我可以使用以下方法使程序正常工作:
char entered[128];
//and then
char exceptions[11] = "aeiouAEIOU";
**有关上述阵列的快速问题。 当我将缓冲区分配给“ exceptions”时,缓冲区必须为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,所以也许这就是我困惑的地方。 我的理解是,上面的代码将比较它们指向的字符/变量的地址。 *表示“当前位置”,而仅放置指针名称将指示指针持有的值(这是指向的变量的地址)。 使用&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。因此,它看不到等效的字符。
使用字符串我在做什么错?
忘记指针 。
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]){
您似乎正在计算字符串中的元音数量。 与其手动写出for循环并建立一个字符串, count_if
使用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());
}
我已经在评论中回答了您与C有关的问题。
至于您对std::string
,实际上是出于某种原因尝试使用std::string*
。 不要那样做 只需使用std::string
; 运算符[]
已重载,无法按原样工作。 目前,您正在将cPtrI
视为字符串数组的元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.