Chinaunix
标题:
range-based for循环无法编译的问题【已解决】
[打印本页]
作者:
vesontio
时间:
2014-10-22 09:17
标题:
range-based for循环无法编译的问题【已解决】
本帖最后由 vesontio 于 2014-10-22 09:47 编辑
#include <string>
#include <cctype>
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
using std::string;
int main () {
string str;
cout << "Enter a string: ";
getline(cin, str);
cout << "String entered: " << str << endl;
string::size_type num_punct = 0;
for (auto c : str) {
if (ispunct(c)) {
num_punct ++;
}
}
cout << "Number of punctuation characters: " << num_punct << endl;
return 0;
}
复制代码
最近在看C++ Primer,里面有一个循环检测字符是否为标点符号的例子。但是编译的时候总是出错:
g++ -std=c++0x -pedantic test_punct.cpp -o test_punct
test_punct.cpp: In function ‘int main()’:
test_punct.cpp:18: error: expected initializer before ‘:’ token
test_punct.cpp:27: error: expected primary-expression at end of input
test_punct.cpp:27: error: expected ‘;’ at end of input
test_punct.cpp:27: error: expected primary-expression at end of input
test_punct.cpp:27: error: expected ‘)’ at end of input
test_punct.cpp:27: error: expected statement at end of input
test_punct.cpp:27: error: expected ‘}’ at end of input
复制代码
书中是说for each这种用法是在C++11标准中方可使用的,我在编译的时候也却是有要求使用-std=c++0x,但是还是出错。
放狗搜索说需要gcc/g++ 4.4.6以后的版本才可编译。我--version了一下,我CentOS 6.5用的是4.4.7,应该可以的啊。
所以不知道问题具体出在哪里,望各位大侠指点!!
作者:
hellioncu
时间:
2014-10-22 09:35
g++版本还是太低,我试了用4.8.2就可以了
作者:
vesontio
时间:
2014-10-22 09:46
回复
2#
hellioncu
如此这般?!
多谢楼上的回复,我CentOS 6.5里面最新也就4.4.7了,既然如此,就先不管它了。
再次感谢回复。
作者:
vesontio
时间:
2014-10-22 10:06
刚刚用Windows下的MinGW编译通过,g++版本是4.8.1。
作者:
socay2
时间:
2014-10-22 22:56
for (auto c : str)
复制代码
这种写法 现在都支持了? 真先进!
作者:
vesontio
时间:
2014-10-22 23:18
回复
5#
socay2
恩的,《C++ Primer 5th Edition》中有标明是C11标准的。
欢迎光临 Chinaunix (http://bbs.chinaunix.net/)
Powered by Discuz! X3.2