To check at an index whether it's a consonant or a vowel , and having a bit of a problem with the writing of the logic in syntactical form?
Tried running it but the count variable wasn't incrementing.
if (s[i]!= ('a' || 'e' || 'i' || 'o' || 'u') && s[i+1] == ('a' || 'e' || 'i' || 'o' || 'u'))
It keeps giving 0 , i.e , the initialised value as the output.
Write a function. For example:
bool isvowel( char c ) {
return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
}
Then you can simply say:
if ( !isvowel( s[i] ) && isvowel( s[i+1] ) ) {
// do something
}
Write a separate function that checks whether a given character is a vowel. For example
#include <iostream>
#include <string>
#include <cstring>
#include <cctype>
bool is_vowel( char c )
{
const char *vowels = "aeiou";
return c != '\0' && std::strchr( vowels, std::tolower( ( unsigned char )c ) );
}
int main( void )
{
std::string s( "Hi" );
if ( not is_vowel( s[0] ) && is_vowel( s[1] ) ) std::cout << s << '\n';
}
The program output is
Hi
Related
I want to iterate char by char in a vector of strings. In my code I created a nested loop to iterate over the string, but somehow I get an out of range vector.
void splitVowFromCons(std::vector<std::string>& userData, std::vector<std::string>& allCons, std::vector<std::string>& allVows){
for ( int q = 0; q < userData.size(); q++){
std::string userDataCheck = userData.at(q);
for ( int r = 0; r < userDataCheck.size(); r++){
if ((userDataCheck.at(r) == 'a') || (userDataCheck.at(r) == 'A') || (userDataCheck.at(r) == 'e') || (userDataCheck.at(r) == 'E') || (userDataCheck.at(r) == 'i') || (userDataCheck.at(r) == 'I') || (userDataCheck.at(r) == 'o') || (userDataCheck.at(r) == 'O') || (userDataCheck.at(r) == 'u') || (userDataCheck.at(r) == 'U')){
allVows.push_back(userData.at(r));
}
else if ((userDataCheck.at(r) >= 'A' && userDataCheck.at(r) <= 'Z') || (userDataCheck.at(r) >= 'a' && userDataCheck.at(r) <= 'z')){
allCons.push_back(userData.at(r));
}
else {
continue;;
}
}
}
}
The error here is in these lines:
allVows.push_back(userData.at(r));
allCons.push_back(userData.at(r));
the r variable is your index into the current string, but here you're using it to index into the vector, which looks like a typo to me. You can make this less error prone using range-for loops:
for (const std::string& str : userData) {
for (char c : str) {
if (c == 'a' || c == 'A' || ...) {
allVows.push_back(c);
}
else if (...) {
....
}
}
}
which I hope you'll agree also has the benefit of being more readable due to less noise. You can further simplify your checks with a few standard library functions:
for (const std::string& str : userData) {
for (char c : str) {
if (!std::isalpha(c)) continue; // skip non-alphabetical
char cap = std::toupper(c); // capitalise the char
if (cap == 'A' || cap == 'E' || cap == 'I' || cap == 'O' || cap == 'U') {
allVows.push_back(c);
}
else {
allCons.push_back(c);
}
}
}
Since this question is about debugging actually, I think it is a nice illustration of how the usage of std::algorithms of C++ can decrease the effort needed to see what is wrong with a non working code.
Here is how it can be restructured:
bool isVowel(char letter)
{
return letter == 'A' || letter == 'a' ||
letter == 'E' || letter == 'e'||
letter == 'O' || letter == 'o'||
letter == 'Y' || letter == 'y'||
letter == 'U' || letter == 'u';
}
bool isConsonant(char letter)
{
return std::isalpha(letter) && !isVowel(letter);
}
void categorizeLetters(const std::vector<std::string> &words, std::vector<char> &vowels, std::vector<char> &consonants)
{
for( const std::string &word : words){
std::copy_if(word.begin(), word.end(), std::back_inserter(vowels), isVowel);
std::copy_if(word.begin(), word.end(), std::back_inserter(consonants), isConsonant);
}
}
With a solution like this, you avoid the error-prone access-with-index that lead to your problem. Also, code is readable and comprehensive
I'm not getting errors, but the output is incorrect. I'm not sure what I'm doing wrong. I can only use functions from string library.
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
int main() {
string message, pig_message;
getline(cin, message);
unsigned int x = message.find_first_of("aeiou");
if (message[x] == 'a' || 'e' || 'i' || 'o' || 'u' ) {
pig_message = message + "yay";
cout << pig_message;
}
else if (!(message[x] == 'a' || 'e' || 'i' || 'o' || 'u' )) {
pig_message = message.substr(1) + message[0] + "ay";
cout << pig_message;
}
system("pause");
return 0;
}
The first if statement is always true. You should change it to
if (message[x] == 'a' || message[x] == 'e' || message[x] == 'i' || message[x] == 'o' || message[x] == 'u' ) {
Also, you could change the else if (...) { line to just
else {
if you want it to be executed every time the first if statement is not true.
Your comparison statement is incorrect.
Make sure your function is actually iterating through the letters, and that you're concatenating the strings correctly.
So:
unsigned int x = message.find_first_of("aeiou"); // Returns the first match
if(message[x] == 'a' || message[x] == 'e'...) // Currently your code reads as only checking for a.
Think of it as IF message[x] = a, IF e, IF i
vs
if message[x] = a, IF message[x] = i
What does your code do after it finds a match?
pig_message = message + 'yay' would add "yay" to the whole message string.
It would then print it out and move on, without doing anything to the other vowels.
I'm new to C++ myself but that's how I've understood your code.
It might be better to go through the whole input string one letter at a time in a for loop with your if else statements to add the strings inside the loop.
I'm building a standard four-function calculator and I've come across a confusing bug.
char Engine::AskUser(){
char type;
std::cout << "'a'dd, 'm'ulitply, 's'ubract, or 'd'ivide ?\n";
std::cin >> type;
CheckUser(type);
return type;
}
void Engine::CheckUser(char uType){
if(uType != 'a' || uType != 's' || uType != 'm' || uType != 'd'){
std::cout << "Type 'a', 'm', 's', or 'd'\n";
AskUser();
}
else
return;
}
What happens is, even if I enter a, s, m, or d, the if statement still iterates as if those conditions were true, which is clearly not the case. I don't get it. Is uType not carrying the value of type from AskUser(), or something similar?
if(uType != 'a' || uType != 's' || uType != 'm' || uType != 'd')
A char is either not equal to 'a', or it is equal to 'a', in which case it's not equal to 's', so this condition is always true.
It should be logical AND:
if(uType != 'a' && uType != 's' && uType != 'm' && uType != 'd')
your if conditional is doing the following check:
if value is not equal to a --
or
if value is not equal to s --
or
if value is not equal to m --
or
if value is not equal to d --
regardless of what char variable uType is, it will always NOT BE at least 3 of the previous 4 variables, hence the if conditional will always result in a TRUE value.
Edited: What I believe you wanted to do was the following:
if ( (uType == 'a') || (uType == 's') || ......)
{
return;
}
else
{
...//The code you previously had if it were true
}
In this case, you would return whenever uType was 1 of the 4 values, otherwise you would implement your code.
Change this line -
if(uType != 'a' || uType != 's' || uType != 'm' || uType != 'd')
to this -
if(uType != 'a' && uType != 's' && uType != 'm' && uType != 'd')
It will surely work.
Here is a problem I have , I have a vector of filenames and I want to check if they end by .jpg or by .png so I made some code with iterators and the STL, this i also for creating a std::map with those names as keys and with value a texture, so here is my code, that does a Segmentation Fault error at the line 11:
#include "TextureManager.h"
std::map<std::string,sf::Texture> createTextureArray(){
std::map<std::string,sf::Texture> textureArray;
std::vector<std::string>::iterator strIt;
std::string fName;
for(strIt = textureFileList().begin(); strIt != textureFileList().end(); strIt++){
sf::Texture texture;
fName = *strIt;
if(fName[fName.size()] == 'g' && fName[fName.size()-1] == 'p' && fName[fName.size()-2] == 'j' && fName[fName.size()-3] == '.'){
texture.loadFromFile(fName);
textureArray[fName] = texture;
}
else if(fName[fName.size()] == 'g' && fName[fName.size()-1] == 'n' && fName[fName.size()-2] == 'p' && fName[fName.size()-3] == '.'){
texture.loadFromFile(fName);
textureArray[fName] = texture;
}
}
return textureArray;
}
I think this is the only code needed to try to understand the problem , but if anyone wants more of this code here is the Github repo
This is not shown in your question, but textureFileList returns by value, which means that you get a copy of the std::vector<std::string> it returns. You're calling this function twice, once for begin() and then once for end(), which means you're calling those functions on different copies of the vector. Obviously the beginning of one copy has no relation to the end of another copy. Not only this, but those copies are being destroyed immediately afterwards, because they are temporaries. Instead, you should store a single copy and call begin and end on that:
std::vector<std::string> fileList = textureFileList();
for(strIt = fileList.begin(); strIt != fileList.end(); strIt++){
And fName[fName.size()] is always '\0'.
You should use
if(fName[fName.size()-1] == 'g' && fName[fName.size()-2] == 'p' && fName[fName.size()-3] == 'j' && fName[fName.size()-4] == '.'){
and
else if(fName[fName.size()-1] == 'g' && fName[fName.size()-2] == 'n' && fName[fName.size()-3] == 'p' && fName[fName.size()-4] == '.'){
I suppose that function textureFileList() returns an object of type std::vector<std::string> by reference.
The segmentation fault can occur due to accessing non-existent character of a string.
if(fName[fName.size()] == 'g' && fName[fName.size()-1] == 'p' && fName[fName.size()-2] == 'j' && fName[fName.size()-3] == '.'){
There is no such character of the string with index fName.size(). The valid range of indexes is 0, size() -1 provided that size() is not equal to zero.
You should use another approach. You have to find the period using member function rfind() and then compare the substring with a given extension.
Here is an example
#include <iostream>
#include <string>
int main()
{
std::string s( "SomeFile.jpg" );
std::string::size_type n = s.rfind( '.' );
if ( n != std::string::npos && s.substr( n ) == ".jpg" )
{
std::cout << "It is a JPEG file" << std::endl;
}
return 0;
}
The output is
It is a JPEG file
Your for loop could be written the following way
for ( const std::string &fName : textureFileList() )
{
const char *ext[] = { "jpg", "png" };
std::string::size_type n = s.rfind( '.' );
if ( n != std::string::npos &&
( fName.substr( n + 1 ) == ext[0] || fName.substr( n + 1 ) == ext[1] ) )
{
sf::Texture texture;
texture.loadFromFile( fName );
textureArray[fName] = texture;
}
}
If you need to erase the extension then you can write simply
fName.erase( n );
In this case fName has to be defined as a non-const reference in the for statement.
I search the most concise and efficient way to find the first printf format sequence (conversion specification) in a C++ string (I cannot use std::regex as they are not yet implement in most in compilers).
So the problem is to write an optimized function that will return the beginning of the first printf-format sequence pos and its length n from an input string str:
inline void detect(const std::string& str, int& pos, int& n);
For example, for:
%d -> pos = 0 and n = 2
the answer is: %05d -> pos = 15 and n = 4
the answer is: %% %4.2f haha -> pos = 18 and n = 5
How to do that (clever and tricky ways are welcome)?
Scan forward for %, then parse the content from there. There are some quirky ones, but not THAT bad (not sure you want to make it an inline tho').
General principle (I'm just typing as I go along, so probably not the BEST form of code ever written - and I haven't tried to compile it at all).
inline void detect(const std::string& str, int& pos, int& n)
{
std::string::size_type last_pos = 0;
for(;;)
{
last_pos = str.find('%', last_pos)
if (last_pos == std::string::npos)
break; // Not found anythin.
if (last_pos == str.length()-1)
break; // Found stray '%' at the end of the string.
char ch = str[last_pos+1];
if (ch == '%') // double percent -> escaped %. Go on for next.
{
last_pos += 2;
continue;
}
pos = last_pos;
do
{
if (isdigit(ch)) || ch == '.' || ch == '-' || ch == '*' ||
ch == '+' || ch == 'l' || ch == 'L' || ch == 'z' ||
ch == 'h' || ch == 't' || ch == 'j' || ch == ' ' ||
ch == '#' || ch == '\'')
{
last_pos++;
ch = str[last_pos+1];
}
else
{
// The below string may need appending to depending on version
// of printf.
if (string("AacdeEfFgGiopusxX").find(ch) != std::string::npos)
{
// Do something about invalid string?
}
n = last_pos - pos;
return;
}
} while (last_pos < str.length());
}
}
edit2: This bit is probably better written as:
if (isdigit(ch)) || ch == '.' || ch == '-' || ch == '*' ||
ch == '+' || ch == 'l' || ch == 'L' || ch == 'z' ||
ch == 'h' || ch == 't' || ch == 'j' || ch == ' ' ||
ch == '#' || ch == '\'') ...
if (string("0123456789.-*+lLzhtj #'").find(ch) != std::string::npos) ...
Now, that's your homework done. please report back with what grade you get.
Edit: It should be noted that some things that a regular printf will "reject" is accepted by the above code, e.g. "%.......5......6f", "%5.8d", "%-5-6d" or "%-----09---5555555555555555llllld". If you want the code to reject these sort of things, it's not a huge amount of extra work, just need a little bit of logic to check "have we seen this character before" in the "check for special characters or digit", and in most cases the special character should only be allowed once. And as the comment says, I may have missed a couple of valid format specifiers. It gets further trickier if you also need to cope with "this 'l' is not allowed with 'c'" or such rules. But if the input isn't "malicious" (e.g. you want to annotate where on which line there are format specifiers in a working C source file), the above should work reasonably well.