免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2802 | 回复: 5
打印 上一主题 下一主题

[C++] range-based for循环无法编译的问题【已解决】 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2014-10-22 09:17 |只看该作者 |倒序浏览
本帖最后由 vesontio 于 2014-10-22 09:47 编辑
  1. #include <string>
  2. #include <cctype>
  3. #include <iostream>

  4. using std::cin;
  5. using std::cout;
  6. using std::endl;
  7. using std::string;

  8. int main () {
  9.   string str;
  10.   cout << "Enter a string: ";
  11.   getline(cin, str);
  12.   cout << "String entered: " << str << endl;

  13.   string::size_type num_punct = 0;

  14.   for (auto c : str) {
  15.     if (ispunct(c)) {
  16.       num_punct ++;
  17.     }
  18.   }

  19.   cout << "Number of punctuation characters: " << num_punct << endl;

  20.   return 0;
  21. }
复制代码
最近在看C++ Primer,里面有一个循环检测字符是否为标点符号的例子。但是编译的时候总是出错:
  1. g++ -std=c++0x -pedantic test_punct.cpp -o test_punct
  2. test_punct.cpp: In function ‘int main()’:
  3. test_punct.cpp:18: error: expected initializer before ‘:’ token
  4. test_punct.cpp:27: error: expected primary-expression at end of input
  5. test_punct.cpp:27: error: expected ‘;’ at end of input
  6. test_punct.cpp:27: error: expected primary-expression at end of input
  7. test_punct.cpp:27: error: expected ‘)’ at end of input
  8. test_punct.cpp:27: error: expected statement at end of input
  9. 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,应该可以的啊。

所以不知道问题具体出在哪里,望各位大侠指点!!

论坛徽章:
324
射手座
日期:2013-08-23 12:04:38射手座
日期:2013-08-23 16:18:12未羊
日期:2013-08-30 14:33:15水瓶座
日期:2013-09-02 16:44:31摩羯座
日期:2013-09-25 09:33:52双子座
日期:2013-09-26 12:21:10金牛座
日期:2013-10-14 09:08:49申猴
日期:2013-10-16 13:09:43子鼠
日期:2013-10-17 23:23:19射手座
日期:2013-10-18 13:00:27金牛座
日期:2013-10-18 15:47:57午马
日期:2013-10-18 21:43:38
2 [报告]
发表于 2014-10-22 09:35 |只看该作者
g++版本还是太低,我试了用4.8.2就可以了

论坛徽章:
0
3 [报告]
发表于 2014-10-22 09:46 |只看该作者
回复 2# hellioncu


如此这般?!

多谢楼上的回复,我CentOS 6.5里面最新也就4.4.7了,既然如此,就先不管它了。

再次感谢回复。

论坛徽章:
0
4 [报告]
发表于 2014-10-22 10:06 |只看该作者
刚刚用Windows下的MinGW编译通过,g++版本是4.8.1。

论坛徽章:
1
巨蟹座
日期:2014-03-18 23:44:30
5 [报告]
发表于 2014-10-22 22:56 |只看该作者
  1. for (auto c : str)
复制代码
这种写法 现在都支持了?  真先进!

论坛徽章:
0
6 [报告]
发表于 2014-10-22 23:18 |只看该作者
回复 5# socay2

恩的,《C++ Primer 5th Edition》中有标明是C11标准的。
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP