2012-11-03 50 views
0

剛回到C++編程。 錯誤我得到:String Char迭代器

用於構件開始在發送的請求是非類類型的炭[30]

請求構件端中發送的非類類型的炭[30]

char sent[] = "need to break this shiat down"; 
    for(vector<string>::iterator it=sent.begin(); it!=sent.end(); ++it){ 
     if(*it == " ") 
      cout << "\n"; 
     else 
      cout << *it << endl; 
    } 

我應該改變字符串還是以不同的方式定義向量?

+0

錯誤VAR聲明,應該是char [] =發送 「需要打破這種shiat下」 – imulsion

+1

@imulsion的聲明是正確的。 –

回答

3

您還可以使用流式傳輸來釋放空白並引入換行符。

#include <iostream> 
#include <sstream> 
#include <string> 
using namespace std; 

int main(int argc, char *argv[]) 
{ 
    stringstream ss("need to break this shiat down.", ios_base::in); 

    string s; 
    while (ss >> s) 
     cout << s << endl; 

    return EXIT_SUCCESS; 
} 

結果:

需要

突破

shiat
下來。

+0

看起來像是分割「」(空格)的最簡單的解決方案。 – IAbstract

1

您的變量sent不是vector<string>,而是char[]

然而,您的for循環會嘗試遍歷字符串向量

對於普通數組,用C迭代:

int len = strlen(sent); 
for (int i = 0; i < len; i++) 
1

使用string代替char[]

string sent = "need to break this shiat down"; 
for(string::iterator it=sent.begin(); it!=sent.end(); ++it){ 
    if(*it == ' ') 
     cout << "\n"; 
    else 
     cout << *it << endl; 
} 

char[]不必須開始和結束的方法..

3

已經指出在其他答案,你正在迭代錯誤的類型。您應該將sent定義爲std::string類型,並使用std::string::begin()std::string::end()進行迭代,或者如果您有C++ 11支持,則可以通過一些選項輕鬆地迭代固定大小的數組。您可以使用迭代和std::begin的std :: end`:

char sent[] = "need to break this shiat down"; 
for(char* it = std::begin(sent); it != std::end(sent); ++it){ 
    if(*it == ' ') 
     std::cout << "\n"; 
    else 
     std::cout << *it << "\n"; 
} 

,或者您可以使用基於範圍的循環:

char sent[] = "need to break this shiat down"; 
for (const auto& c : sent) 
{ 
    std::cout << c << "\n"; 
} 
2

char sent[]不是std::string但字符串文本 - 但在這個非常情況下,你可以遍歷它:

int main() { 
char sent[] = "need to break this shiat down"; 
    for(auto it = std::begin(sent); it!=std::end(sent) - 1; ++it){ 
     if(*it == ' ') 
      cout << "\n"; 
     else 
      cout << *it << endl; 
    } 
} 

注意,我改變" "' ' - 和去年跳過空終止符'\0' ...

活生生的例子:http://liveworkspace.org/code/55f826dfcf1903329c0f6f4e40682a12

對於C++ 03,你可以用這個辦法:

int main() { 
char sent[] = "need to break this shiat down"; 
    for(char* it = sent; it!=sent+sizeof(sent) - 1; ++it){ 
     if(*it == ' ') 
      cout << "\n"; 
     else 
      cout << *it << endl; 
    } 
} 

如果這是字符串常量在這一點上不知道大小 - 使用strlen代替sizeof ...