mardi 6 septembre 2016

Warning C4244 \ '=': conversion from 'int' to 'char', possible loss of data?

Hello I was solving some online C++ questions. Question was: Write a function that checks if a given sentence is a palindrome. A palindrome is a word, phrase, verse, or sentence that reads the same backward or forward. Only the order of English alphabet letters (A-Z and a-z) should be considered, other characters should be ignored.

For example, isPalindrome("Noel sees Leon.") should return true as spaces, period, and case should be ignored resulting with "noelseesleon" which is a palindrome since it reads same backward and forward.

My Solution:

#include <iostream>
#include <string>
#include <stdexcept>
#include <algorithm>
#include <iterator>
#include <sstream>
using namespace std;

class Palindrome
{
public:
  static bool isPalindrome(std::string str)
  {
    int n = str.length();
    str.resize(remove_if(str.begin(), str.end(), [](char x) {return !isalnum(x) && !isspace(x); }) - str.begin());
    for (int i = 0; i < n; i++) {
        str[i] = toupper(str[i]); // makes all letters capital

    }

    if (std::equal(str.begin(), str.begin() + str.length() / 2, str.rbegin()))
        return true;
    else
        return false;
}
 };

 #ifndef RunTests
 int main()
 {
  std::cout << Palindrome::isPalindrome("Noel sees Leon.");
  return 0;
 }
 #endif

I am using c++11. I believe I have proper output however I fail in one case which generates the warning: "Warning C4244 \ '=': conversion from 'int' to 'char', possible loss of data? at cpp(17) which is at this point of the code in my class function":

for (int i = 0; i < n; i++) {
        str[i] = toupper(str[i]); // to make all letters capital            
    }

Please can someone say what can I do to get rid of this error.

Aucun commentaire:

Enregistrer un commentaire