【发布时间】: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& c : yourString)。这是一种更现代的方式。虽然在这种情况下并没有真正的区别,但它看起来更好。