I'm pretty new to coding in C++ and need your help. In the code below I want to check for Parlindrome and show the reversed text. So if I run this code, it displays the right reversed words, but dont return them true if checked for parlindrome.
The console shows:
madam0
ada0
ecalevol0
Why the return is always 0?
Thanks for your help!
#include <iostream>
// Define is_palindrome() here:
bool is_palindrome(std::string text) {
std::string text_reversed;
for(int i = text.length(); i >= 0; i-- ) {
text_reversed += text[i];
std::cout << text[i];
}
if (text_reversed == text) {
return true;
} else {
return false;
}
}
int main() {
std::cout << is_palindrome("madam") << "\n";
std::cout << is_palindrome("ada") << "\n";
std::cout << is_palindrome("lovelace") << "\n";
}
Your i starts at text.length(), not text.length() - 1.
So, your first text[i] is a null byte (yes, even for std::string, this is guaranteed).
Thus the first character of text_reversed is a "hidden" character that was not present in text, and the two will never match.
std::string reversed_string(const std::string& s)
{
return {s.rbegin(), s.rend()};
}
bool is_palindrome(const std::string& s)
{
return std::equal(s.begin(), s.begin() + s.size() / 2, s.rbegin());
}
Documentation of std::equal has example of is_palindrome
Your biggest problems there are i>=0 and text[i]. It should be i>0 and text[i-1].
And please simplify that return statement.
#include <iostream>
bool is_palindrome(std::string text) {
std::string text_reversed = "";
for(int i = text.length(); i > 0; i-- ) {
text_reversed += text[i-1];
}
std::cout << text_reversed <<std::endl;
std::cout << text <<std::endl;
return text == text_reversed;
}
int main() {
std::cout << is_palindrome("madam") << std::endl;
std::cout << std::endl;
std::cout << is_palindrome("ada") << std::endl;
std::cout << std::endl;
std::cout << is_palindrome("lovelace") << std::endl;
std::cout << std::endl;
}
Related
I have the following code, where I try to insert values into a multimap of 2 strings, but I keep getting an error that I cannot understand. I've been trying to solve this for hours.
The whole point of the program is to sort the lines of a dictionary based on the automatic sorting of the multimap insertion.
// sort_entries_of_multiple_dictionaries.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <iostream>
#include <fstream>
#include <vector>
#include <map>
#include <string>
#include <algorithm>
#include <iomanip>
#include <sstream>
// Prototypes
int indexDict(std::multimap<std::string, std::string>& dict);
int main()
{
std::multimap<std::string, std::string> dict;
if(indexDict(dict) == 0)
return 0;
}
int indexDict(std::multimap<std::string, std::string>& dict)
{
std::ifstream inputFile{ "output.txt", std::ios::in };
std::string currentDictEntry{};
size_t currentLine{};
if (!inputFile)
{
std::cerr << "input.txt FILE NOT FOUND in the current directory" << std::endl;
system("pause");
return 0;
}
while (std::getline(inputFile, currentDictEntry))
{
//std::cout << currentDictEntry << std::endl; // TO DELETE
std::string currentWord{};
size_t delimiterPos = currentDictEntry.find('\t', 0);
if (delimiterPos == std::string::npos)
std::cerr << "ERROR. Delimiter \"<b>\" not found in line " << currentLine << std::endl;
else
{
//std::cout << "pos of \\t = " << delimiterPos << std::endl; // TO DELETE
for (char& ch : currentDictEntry)
{
if (ch != '\t')
{
currentWord += ch;
}
else
break;
}
std::cout << currentWord /* << '|' */ << std::endl; // TO DELETE
auto value = currentDictEntry.substr(delimiterPos, std::string::npos);
std::cout << "size= " << value.size() << '|' << value << std::endl;
dict.insert( currentWord, currentWord/*, value*/ );
}
if (currentLine == 50) return 0; // TO DELETE
currentLine++;
}
return 1;
}
if (currentLine == 50) return 0; // TO DELETE
currentLine++;
}
return 1;
}
The error I keep getting is:
unary '++': '_Iter' does not define this operator or a conversion to a type acceptable to the predefined operator
illegal indirection
as #Evg said, it accepts a std::pair
dict.insert(std::make_pair(currentWord, value));
if I understand your intention correctly, you don't want to save the \t into your result, so add 1 after delimiterPos to get the correct value:
auto value = currentDictEntry.substr(delimiterPos + 1, std::string::npos);
test run. output.txt:
4 d
1 a
2 b
3 c
0
output:
"0" - ""
"1" - "a"
"2" - "b"
"3" - "c"
"4" - "d"
full code:
#include <iostream>
#include <fstream>
#include <map>
#include <string>
#include <iomanip>
#include <sstream>
// Prototypes
int indexDict(std::multimap<std::string, std::string>& dict);
int main()
{
std::multimap<std::string, std::string> dict;
if (indexDict(dict) == 0)
return 0;
for (auto& i : dict) {
std::cout << "\"" << i.first << "\" - \"" << i.second << "\"\n";
}
}
int indexDict(std::multimap<std::string, std::string>& dict)
{
std::ifstream inputFile{ "output.txt", std::ios::in };
std::string currentDictEntry{};
size_t currentLine{};
if (!inputFile)
{
std::cerr << "output.txt FILE NOT FOUND in the current directory" << std::endl;
system("pause");
return 0;
}
while (std::getline(inputFile, currentDictEntry))
{
//std::cout << currentDictEntry << std::endl; // TO DELETE
std::string currentWord{};
size_t delimiterPos = currentDictEntry.find('\t', 0);
if (delimiterPos == std::string::npos)
std::cerr << "ERROR. Delimiter \"<b>\" not found in line " << currentLine << std::endl;
else
{
//std::cout << "pos of \\t = " << delimiterPos << std::endl; // TO DELETE
for (char& ch : currentDictEntry)
{
if (ch != '\t')
{
currentWord += ch;
}
else
break;
}
std::cout << currentWord /* << '|' */ << std::endl; // TO DELETE
auto value = currentDictEntry.substr(delimiterPos + 1, std::string::npos);
std::cout << "size= " << value.size() << '|' << value << std::endl;
dict.insert(std::make_pair(currentWord, value));
}
if (currentLine == 50) return 0; // TO DELETE
currentLine++;
}
return 1;
}
small mistakes in your code: you don't need <algorithm> and <vector>. also your error message said input.txt instead of output.txt.
I Change dict.insert( currentWord, currentWord/*, value*/ ); To dict.insert({ currentWord,currentWord }); and error Has solved
It's a bit weird to me that the code after a for loop doesn't execute but the compiler doesn't raise any warning:
#include <iostream>
#include <iterator>
bool isVowel(char ch)
{
char vowels[]{"aeiouAEIOU"};
char *p = std::find(std::begin(vowels), std::end(vowels), ch);
if (p != std::end(vowels))
{
std::cout << ch << " is a vowel" << '\n';
return true;
}
else
{
std::cout << ch << " is not a vowel" << '\n';
return false;
}
}
int main()
{
char name[]{"MollieU"};
int numVowels{0};
std::cout << name << '\n';
int length{std::size(name)};
for (char* ptr{name}; ptr < (name + length); ++ptr)
{
if (isVowel(*ptr))
++numVowels;
}
std::cout << name << " has " << numVowels << " vowels." << '\n';
return 0;
}
It has outputs like:
MollieU
M is not a vowel
o is a vowel
l is not a vowel
l is not a vowel
i is a vowel
e is a vowel
U is a vowel
But std::cout << name << " has " << numVowels << " vowels." << '\n'; is never run. Whatever code I put after the loop is never run. I am not sure if return 0 is run or not, but the file is compiled successfully. I am using g++ -std=c++2a on osx.
Try to use the following:
int length { std::size(name) - 1 };
I'm working on a project which needs to find the number of words and the indices of each word in the paragraph ...I have written the code which is counting the number of word in a string but I stuck with finding the indices of words,
such as : Hi John How are you I miss you ..
I need to print the indices like : 0 1 2 3 4 5 6 7
here is the code:
int _tmain(int argc, _TCHAR* argv[])
{
int count_words(std::string);
std::string input_text;
std::cout<< "Enter a text: ";
std::getline(std::cin,input_text);
int number_of_words=1;
int counter []={0};
for(int i = 0; i < input_text.length();i++)
if(input_text[i] == ' ')
number_of_words++;
std::cout << "Number of words: " << number_of_words << std::endl;
//std:: cout << number_of_words << std::endl;
system ("PAUSE");
}
Hopefully this helps. Edited to include use of count_words function.
#include <iostream>
#include <sstream>
void count_words(std::string);
int main(){
std::string input_text, output_text;
std::cout<< "Enter a text: ";
std::getline(std::cin,input_text);
count_words(input_text);
system ("PAUSE");
return 0; //MUST RETURN AN INTEGER VALUE FROM 'INT MAIN'
}
void count_words(std::string inputString){
std::string output_text;
std::stringstream indexes;
int number_of_words=0; //If there are no words, it would be false, make it 0.
//int counter []={0}; //This serves no purpose.
if(!inputString.empty()){// test to make sure it isn't empty.
number_of_words++;
for(int i = 0; i < inputString.length();i++){ // For loops should have curly braces {} containing their statement.
if(inputString[i] == ' '){
number_of_words++;
}
if((isalpha(inputString[i]))&&inputString[i-1]==' '){ //test for following space separated word
indexes << i << " ";
}
}
}
output_text = indexes.str(); //convert stringstream to string
std::cout << "Number of words: " << number_of_words << std::endl;
//std:: cout << number_of_words << std::endl; //duplicate info
std::cout << "Indexes: " << output_text << std::endl;
}
I'm not sure if i understand the question. You only need print the "indices"?? like this? (Using your own code)
#include <iostream>
#include <vector>
#include <string>
void stringTokenizer(const std::string& str, const std::string& delimiter, std::vector<std::string>& tokens) {
size_t prev = 0, next = 0, len;
while ((next = str.find(delimiter, prev)) != std::string::npos) {
len = next - prev;
if (len > 0) {
tokens.push_back(str.substr(prev, len));
}
prev = next + delimiter.size();
}
if (prev < str.size()) {
tokens.push_back(str.substr(prev));
}
}
int main()
{
std::vector <std::string> split;
std::string input_text;
std::cout<< "Enter a text: ";
std::getline(std::cin,input_text);
stringTokenizer(input_text, " ", split);
int number_of_words = 0;
for (std::vector<std::string>::iterator it = split.begin(); it != split.end(); it++, number_of_words++) {
std::cout << *it << " " << number_of_words << std::endl;
}
}
The value data type is Float. Here I need to validate the value if it is only numbers(int,float) not a string or special character.
Ex: value = 123df.125
How to check value if a string is mixed.
Here I need to display a warning message "the value is not proper".
You may want to try this if you have given a string.
bool contains_digits (const std::string &str)
{
return str.find_first_not_of ("0123456789") == std::string::npos;
}
/* C++ 11 */
bool contains_digits(const std::string &str)
{
return std::all_of (str.begin(), str.end(), ::isdigit);
}
If you are getting the data from user input (The cli or a file, for example), you could check if the read operation fails:
float f;
if( std::cin >> f )
std::cout << "OK, a number value was readed" << std::endl;
else
std::cout << "ERROR: Something that is not a number is at the input, so cin cannot read it as a float" << std::endl;
One more C++11 solution:
#include <iostream>
#include <string>
#include <stdexcept>
int main()
{
std::string wrong{"123df.125"};
std::string totallyWrong{"A123"};
std::string right{"123.125"};
try
{
size_t pos = 0;
float value = std::stof(right, &pos);
if(pos == right.size())
std::cout << "Good value:" << value << "\n";
else
std::cout << "Provided value is partly wrong!\n";
pos = 0;
value = std::stof(wrong, &pos);
if(pos == right.size())
std::cout << "Good value: " << value << "\n";
else
std::cout << "Provided value is partly wrong!\n";
value = std::stof(totallyWrong, &pos);
}
catch(std::invalid_argument&)
{
std::cout << "Value provided is invalid\n";
}
return 0;
}
I have again a strage C++ thing on the following:
l is an incomming line (string.c_str()) > becomes line
pos is the position from where to start searching
s is a string (string.c_str()) to look for > becomes command
It all works fine until command is "-1". In this case the string "-1" is not found although line is containing it.
Am I missing something ovious?
Code:
bool Converter::commandAvailable(const char* l, int pos, const char* s) {
string line = l;
string command = s;
int x = line.find(command, pos);
if (x != -1) {
return true;
}
return false;
}
Thanks in advance!
This should help you find the problem:
bool Converter::commandAvailable(const char* l, int pos, const char* s)
{
string line = l;
string command = s;
std::cout << "INPUT" << std::endl;
std::cout << "LINE: " << line << std::endl;
std::cout << "CMD: " << command << std::endl;
std::cout << "START: " << pos << std::endl << std::endl;
std::size_t x = line.find(command, pos);
std::cout << "OUTPUT: " << x << std::endl;
if (x != std::string::npos)
{
return true;
}
return false;
}