【发布时间】:2010-11-22 05:56:28
【问题描述】:
当我运行这个程序时收到两个警告,我不知道如何阻止这种情况的发生。任何帮助,将不胜感激!
警告:有符号和无符号整数表达式之间的比较
是我在 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"; }
【问题讨论】:
-
在要求解释时包含实际警告真的很有帮助。
-
为什么
swap、reverse_word和extract_word类方法根本不接触类成员?还要注意cplusplus.com/reference/algorithm/reverse的存在@