Zud*_*Zud 0 c++ class function
当我运行这个程序时得到两个警告,我无法弄清楚如何阻止这种情况发生.任何帮助,将不胜感激!
警告:有符号和无符号整数表达式之间的比较
是我在extract_word函数中获得2行的警告.
#include<iostream>
#include<string>
using namespace std;
class StringModify {
public:
void get_data();
//takes a line of input from the user
string& extract_word(string& a);
//extracts each word from the input line
string& reverse_word(string& s);
//returns a string which is reverse of s
void rev();
void swap(char& v1, char& v2);
//interchanges value of v1 and v2
void append(const string& reverse_word);
//puts together each reversed word with whitespaces to get formatted_line
void display();
//diss both input line and formatted_line
private:
string origional_string; //original string
string formatted_string; //formatted string
string word;
};
int main() {
StringModify data1;
//data1 becomes the call for class StringModify
data1.get_data();
// Exicution of get_data in class StringModify
data1.rev();
// Exicution of rev in class StringModify
data1.display();
// Exicution of display in class StringModify
return 0; }
void StringModify::get_data() {
cout << "Enter the string: ";
getline(cin, origional_string); }
string& StringModify::extract_word(string& a) {
size_t position = a.find(" ");
if(position != -1)
{
word = a.substr(0, position);
a.erase (0, position + 1);
}
else
{
word = a;
a = "";
}
return word; }
string& StringModify::reverse_word(string& s) {
for(int i = 0; i < s.length() / 2; i++)
{
swap(s[i], s[s.length() - 1 - i]);
}
return s; }
void StringModify::rev() {
string copy = origional_string;
while (!copy.empty())
{
append(reverse_word(extract_word(copy)));
} }
void StringModify::swap(char& v1, char& v2) {
char temp = v1;
v1 = v2;
v2 = temp; }
void StringModify::append(const string& reverse_word) {
formatted_string += reverse_word + " "; }
void StringModify::display() {
cout << "\nThe original string: "
<< origional_string << "\n"
<< "\nThe formatted string: "
<< formatted_string << "\n"; }
Run Code Online (Sandbox Code Playgroud)
您将结果分配a.find(" ")给a size_t. size_t是一个无符号类型; 它永远不会有负值.
请注意,这并不意味着比较永远不会成立.的-1将被转换为是无符号,以便能够进行所述比较(这是所谓的通常的算术转换部).转换-1为无符号时,它会产生无符号类型可表示的最大值.因此,如果find()返回最大可能size_t,那么比较将产生真.
要解决警告,您应该比较std::string::npos,find()如果找不到该元素,则返回的值.