Chinaunix

标题: range-based for循环无法编译的问题【已解决】 [打印本页]

作者: vesontio    时间: 2014-10-22 09:17
标题: range-based for循环无法编译的问题【已解决】
本帖最后由 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,应该可以的啊。

所以不知道问题具体出在哪里,望各位大侠指点!!
作者: 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
  1. 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