字符串炭迭代仪

String Char Iterator

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

刚刚返回到C 中的编程。我遇到的错误:

请求成员开始发送的启动是非班级类型char [30]

send的会员端的请求是非班级类型char [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;
    }

我应该更改字符串或定义向量的字符串还是不同?

在其他答案中指出,您正在迭代错误的类型。您应该将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";
}

您也可以使用流式扔掉空格并扔进新线。

#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
下来。

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;
    }
}

请注意,我将" "更改为 ' '-并跳过了最后一个null终止char '' ...

实时示例:http://liveworkspace.org/code/55f826dfcf1903329c0f6f6f4e40682a12

对于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 ...

您的变量 sent不是类型vector<string>,而是char[]

但是,您的循环尝试在字符串的向量中尝试迭代。

对于平原阵列,使用C迭代:

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

使用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[]没有开始和结束方法。