无法使用 Ubuntu 解决C++构建中的声明和循环错误

Can't solve declaration and loop errors in C++ building with Ubuntu

本文关键字:声明 错误 循环 构建 C++ Ubuntu 解决      更新时间:2023-10-16

由于这两个错误,我的项目无法构建,而且我一直无法弄清楚如何修复它们。其中一个我认为与我的GCC/G ++版本有关,但我有4.7,我很确定c ++ 11。我不确定另一个"it"声明错误。

我的代码:

#include "stdafx.h"
using namespace std;
#include <iostream>
#include <string>
void encrypt(std::string &iostr, int key) {
key %= 26;
int ch;
for (auto &it : iostr) {
ch = tolower(it);
if (!islower(ch)) {
continue;
}
ch += key;
if (ch > 'z') {
ch -= 26;
}
it = ch;
}
}
int main() {
string source;
int key = 1;
cout
<< "Paste cyphertext and press enter to shift each letter right 1";
getline(cin, source);
encrypt(source, key);
cout << source << "";
encrypt(source, key);
cout << source << endl;
cout << "Press ENTER to exit";
cin.ignore(cin.rdbuf()->in_avail() + 1);
return 0;
}

错误:

test.cpp: In function ‘void encrypt(std::string&, int)’:
test.cpp:10:13: error: ISO C++ forbids declaration of ‘it’ with no type   
[-fpermissive]
test.cpp:10:18: error: range-based ‘for’ loops are not allowed in C++98 mode

这些错误是怎么回事,我该如何修复它们?提前感谢您的帮助,非常感谢。

你需要编译器选项-std=c++11

并评论您的第一个头文件,因为您使用的是 gcc,我认为它是特定于 Windows 的:

//#include "stdafx.h"

错误消息

error: range-based ‘for’ loops are not allowed in C++98 mode

清楚地表明您正在 C++98 模式下使用 G++。

使用命令行选项 -std=c++11 使用 C++11 模式进行编译。