[英]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.