【问题标题】:comparing character to space in c++?比较字符与C++中的空格?
【发布时间】:2014-09-14 17:44:21
【问题描述】:

我是 C++ 的新手,具有 Java 和 Python 背景。

最终,对于我需要编写的程序,我需要颠倒字符串中单词的顺序。即“Do or do not there is no try”变成“try no is there not do or Do”

但现在,我只是想将单个单词放入数组/向量中。

#include <iostream>
#include <vector>
using namespace std;
int main()
{
    string x = "There is no knowledge that is not power";
    vector<string> myvector;
    string str = "";
    char spaceman = ' ';

    for( int a = 0; a < x.length(); a++)
    {
        if(x[a].compare(spaceman) != 0)
        {
            str.append(x[a]);
        }
        else
        {
            myvector.push_back(str);
            str = "";
        }
    }


    cout << myvector.at(0) << endl;

    cout << x[0] << endl; //A test on x

    return 0;
}

但是,这会返回以下警告和错误消息(顺便说一下,我使用的是 CodeLite):

warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
for( int a = 0; a < x.length(); a++)
                             ^

error: request for member 'compare' in 'x.std::basic_string<_CharT, _Traits, _Alloc>::operator[]<char, std::char_traits<char>, std::allocator<char> >(((std::basic_string<char>::size_type)a))', which is of non-class type 'char'
if(x[a].compare(spaceman) != 0)
        ^

error: invalid conversion from 'char' to 'const char*' [-fpermissive]
str.append(x[a]);
               ^

我错过了什么?我对 C++ 非常不熟悉。将“spaceman”变量从 char 更改为 string 也没有做任何事情。

【问题讨论】:

  • 只是一点建议:如果您要遍历字符串的字符,请使用for (const auto&amp; c : yourString)。这是一种更现代的方式。虽然在这种情况下并没有真正的区别,但它看起来更好。

标签: c++ arrays vector char


【解决方案1】:

简单地比较一下同类,比如:

if(x[a] == spaceman)
{
    // ...

因为x[a]spaceman 一样是char

【讨论】:

    【解决方案2】:

    首先,您可以更简单地构建向量。例如

    #include <iostream>
    #include <vector>
    #include <sstream>
    #include <iterator>
    
    int main()
    {
        std::string s = "There is no knowledge that is not power";
        std::istringstream is( s );
    
        std::vector<std::string> myvector( ( std::istream_iterator<std::string>( is ) ),
                                             std::istream_iterator<std::string>() );
    
        for ( std::string t : myvector ) std::cout << t << std::endl;
    }
    

    至于你的代码然后在这个for语句中

    for( int a = 0; a < x.length(); a++)
    

    您将有符号整数 a 与无符号 x.length() 进行比较。应该是这样写

    for( std::string::size_type a = 0; a < x.length(); a++)
    

    在此声明中

    if(x[a].compare(spaceman) != 0)
    

    表达式 x[a] 的类型为 char。包括 char 在内的基本类型不是类,也没有方法。

    并且在 std::string 类中没有一个具有 char 类型参数的 append 方法。 所以不是

    str.append(x[a]);
    

    应该有

    str.append(1, x[a]);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-03-27
      • 1970-01-01
      • 1970-01-01
      • 2015-07-15
      • 1970-01-01
      • 2018-01-16
      • 1970-01-01
      相关资源
      最近更新 更多