【问题标题】:my computer won't accept s.length, but other compilers do我的计算机不接受 s.length,但其他编译器可以
【发布时间】:2018-01-12 04:42:11
【问题描述】:

使用某些功能,我的计算机/NetBeans 似乎无法运行我的代码,即使它可以在不同的编译器中运行。这是我的函数(请记住,这不是我的整个项目,我确实有一个 int main()):

#include <iostream>
#include <iomanip>
#include <string>
#include <iterator>
#include <cstdlib>
#include <ctime>
#include <windows.h>
using namespace std;
void convert (string& s){ //Creating a function that makes a variable lower case
    for(int i=0; i<s.length(); i++){ 
        s[i] = tolower(s[i]); //tolower lets me change to lower case
    }
}

我得到的错误是:“无法解析标识符长度”。如果您需要查看我的整个项目,请询问,我不介意,如果没关系就认为这是浪费时间。我正在使用 NetBeans 8.2,在此先感谢

【问题讨论】:

  • 如果你用那个函数和一个空的int main() {}编写一个程序会发生什么?
  • 它是什么编译器?
  • 如果明确使用std::string作为类型会发生什么?
  • @MichaelWalz 您是否声称所有包含都是必需才能重现问题?如果不是,那么它显然是不是最小的。 OP自己承认,提供的代码缺少main;因此它不完整。我无法确认它的可验证性; 可能甚至需要更多信息,例如编译器的实际调用方式。 MCVE 不是一堆任意的字母,意思是一点点代码。点击上面的链接了解更多信息。

标签: c++ string function netbeans netbeans-8


【解决方案1】:

您可以尝试 size() 代替 length() 。对于 C++ 中的 string,它们之间没有显着差异,但 size() 也用于其他 STL 容器,例如 mapvector 等。所以一般来说,人们使用size() 函数。

用法同length(),i &lt; s.size()

【讨论】:

    【解决方案2】:

    看起来好像 std::string 的实现省略了函数 length();顺便说一句,它不返回 int,所以你应该得到一张警告票。以后请发一个完整的程序,包括main()。

    解决旧方法;

    #include <string>
    
    void convert(std::string& s) { //Creating a function that makes a variable lower case
        const size_t sz = s.size();
    
        for (size_t i = 0; i<sz; ++i) {
            s[i] = tolower(s[i]); //tolower lets me change to lower case
        }
    }
    
    int main() {
        std::string s("AbCdEf");
        convert(s);
        return 0;
    }
    

    新奇的方式...

    #include <string>
    
    void convert(std::string& s) { //Creating a function that makes a variable lower case
        for (char &ch : s) {
            ch = tolower(ch); //tolower lets me change to lower case
        }
    }
    
    int main() {
        std::string s("AbCdEf");
        convert(s);
        return 0;
    }
    

    即使是新奇的方式......

    #include <algorithm>
    
    void convert(std::string& s) { //Creating a function that makes a variable lower case
           std::transform(std::begin(s), std::end(s), std::begin(s), ::tolower);
    }
    

    【讨论】:

      猜你喜欢
      • 2019-08-22
      • 2020-09-09
      • 1970-01-01
      • 2012-05-19
      • 2020-02-28
      • 2020-11-26
      • 1970-01-01
      • 1970-01-01
      • 2012-10-17
      相关资源
      最近更新 更多