错误:具有索引或迭代字符串的"<"标记之前的预期初始值设定项

error: expected initializer before ‘<’ token with indexed or iterated string

本文关键字:索引 迭代 错误 lt 字符串      更新时间:2023-10-16

这对我来说是最奇怪的错误。

g++ -Wall -g -std=c++11 *.cpp -o lab2
lab2.cpp: In function ‘void toAlpha(std::string&)’:
lab2.cpp:18:19: error: expected initializer before ‘<’ token
  for(int i = 0, i < str.length(), ++i){
               ^
lab2.cpp:18:19: error: expected ‘;’ before ‘<’ token
lab2.cpp:18:19: error: expected primary-expression before ‘<’ token
lab2.cpp:18:38: error: expected ‘;’ before ‘)’ token
  for(int i = 0, i < str.length(), ++i){
                                  ^

从我读过的内容中。此错误通常来自上述行之上的东西。但是,它几乎是代码中的第一个功能。也许您可以帮助看看我的眼睛无法。

fyi函数的目的是将所有非阿尔法字符转换为空格。

无论我是通过索引还是迭代器访问。

这是代码:

#include <map>
#include <iostream>
#include <set>
#include <fstream>
#include <algorithm>
#include <list>
#include <cctype>
#include <sstream>
#include "print.h"
using namespace std;
typedef map<string,list<int>> WORDMAP;
/* makes symbols turn into spaces */
void toAlpha(string& str){
  for(int i = 0, i < str.length(), ++i){
    if(!isalpha(str[i])){
       str[i] = ' ';
    }
  }
}

您需要在循环语句中使用;

这是由于不正确的 for循环语法

更改:

for(int i = 0, i < str.length(), ++i)

to:

for(int i = 0; i < str.length(); ++i)
//           ^                 ^           

使用semicolons代替逗号:

void toAlpha(string& str){
  for(int i = 0; i < str.length(); ++i){
    if(!isalpha(str[i])){
       str[i] = ' ';
    }
  }
}

for循环语法是这样的:

  for(int i = 0; i < str.length(); ++i){

注意分号而不是逗号。