Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
Hi there I have attached my code below and it is not working. I want to eliminate all possibles except number or character. Also no upper and lower case problem. But I don't know why it's not working even after I've tried this far. Please any help would be appreciated.
// C++ program to find if a sentence is
// palindrome
//#include <bits/stdc++.h>
#include <iostream>
#include <string>
#include <ctype.h>
using namespace std;
// To check sentence is palindrome or not
bool sentencePalindrome(string sentence)
{
int j = 0;
int l = sentence.length() - 1;
// Compares character until they are equal
while (j < l) {
//removing spaces and special characters
while(j<l&& isalnum(sentence[j])==0)
j++;
while(j<l && isalnum(sentence[l])==0)
l--;
//Checking if not palindrome
if(toupper(sentence[j])!=toupper(sentence[l]))
{
return false;
}
else
{
j++;
l--;
}
}
return true;
}
// Driver program to test sentencePalindrome()
int main()
{
string sentence;
cout << "enter sentence!" << endl;
cin >> sentence;
int result = sentencePalindrome(sentence);
if (result==1)
cout << "Sentence is palindrome.";
else
cout << "Sentence is not palindrome.";
return 0;
}
Your main issue appears to be the way you are reading in you input in your Main function. Using >> in C++ will only read in one word at a time, so you are not working with the full sentence in the function sentencePalindrome().
You should look at using getline() instead to be able to read an entire sentence in as input.
If you use the debugger, it is much easier to spot the problem. I took your code above and set a breakpoint right as the variable l is being declared on line 13 (you can see the orange dot to the left of the code for it).
When you reach that breakpoint when running the code, you can see that the value of sentence = "Test" down at the bottom, even though my input at the command line was Test the sentence.
Once you fix how you get input, you can check the logic of your program and see if it functions correctly. If you are unfamiliar with debugging, putting in a little time to learn GDB now will save you hours of frustration while coding in the future!
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I am not a professional programmer but after getting some experience in easy languages like python or matlab, I need to make a little program in C++. For this I try to read user input until the user inputs something sensible - however, this loop never terminates due to my control variable (test2) never being reassigned, even though the corresponding code block is entered. Let me explain in detail:
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include "Header.h"
using namespace std;
int test2; //variable to stay 1 until user has entered suitable input
string input2[2]; //storage for input strings
int MinimalTest() {
test2 = 1; //control variable is set one
cout << "Enter a string." << endl;
do {
//we will enter a string at least once, and we exit this loop only when the input is suitable
std::string line; //complicated input part - a simple getline() command led to weird behaviour
std::getline(std::cin, line);
std::stringstream linestream(line);
linestream >> input2[i];
cout << "input: " << input2[i] << " test: " << test2 << "input bool: " << input2[i].empty() << endl; //this is just for troubleshooting
if (input2[i].empty()) {
//if the user entered an empty string, he needs to do it again
cout << "Your string is empty. Please enter a valid string (non-empty)." << endl;
}
else {
//if he entered a valid string, we can continue with the next input
cout << "I am here." << endl; //This is for trouble shooting. This code block is entered and executed since this gets printed.
test2 = 0;// this gets ignored for some reason. Hence, the loop never terminates.
}
}(while (test2 = 1);
}
So the first loop never terminates. Test2 never gets reassigned to 0, even though the else command is executed. This boggles my mind tbh - it is just a simple assignment operator on an int. Possible output looks like this (Note how I still got a second problem: strings with a space inside get cut off. I would appreciate any feedback on that as well, even though I try to trouble shoot one thing at a time and this post is not aimed at this problem):
Output example
Thank you very much for your consideration!
All the best,
A very confused newbie.
Change your while condition to test2 == 1
test2 = 1 is an assignment, setting the value to 1.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 3 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
My output file is supposed to show to answer to the function it calls on. The program runs fine, however it is not displaying the text in the "prime" function. the output file, when checked, only displays 1's. I believe this is due to the fact that its declared as a bool function, and set to return true. However, how would I get this code to return the solution in Prime to the output file?
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
using namespace std;
bool prime(int);
int main()
{
int reader;
ifstream Infile;
Infile.open("numlist.txt");
ofstream outputFile;
outputFile.open("theoutput.txt");
while (Infile >> reader)
{
outputFile << prime(reader) <<endl;
}
Infile.close();
outputFile.close();
}
bool prime(int p)
{
if (p % 2 == 0)
cout << "\n" << p << "\n Is not a prime number";
else if (p % 2 != 0)
cout << "\n" << p << "\n is a prime number";
return true;
}
No errors, however the output file is only showing 1's.
This is happening because in your prime() function, all the output is going to cout and not into outputFile. The prime() function returns a bool which is what is sent to outputFile.
If you'd like to have output of the function go to outputFile, you can either pass outputFile as a parameter and use that instead of cout or make it global.
A few more comments on your code: you don't need the full else if (p % 2 != 0) in the else statement. You can just use else, because p % 2 is either 0 or it's not, there's no other option.
Also, strongly recommend using braces around if statements, even if they are just a single line.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
Using c++ 14.
I'm prompting the user for a string containing both letters and integers, and trying to "strip" the integers from the string itself via the string.erase() function.
The problem i'm facing is when there are 2 or more sequential numbers, than the function seems to erase the first but delete the latter.
Example:
input: H23ey Th2e3re St01ack O34verflow
output: H3ey There St1ack O4verflow
I can do it another way by using a new string, looping through the existing one and adding only what isalpha or isspace, but it seems messier.
code:
string digalpha {};
cout << "Enter string containing both numbers and letters: ";
getline(cin, digalpha);
for (size_t i {}; i < digalpha.size(); i++)
if (isdigit(digalpha.at(i)))
digalpha.erase(i,1);
cout << digalpha << endl;
cout << endl;
return 0;
In the first sentence you were writing that you are using C++14.
In "more modern" C++ the usage of algorithm is recommended. So normally you would not use C-Style For loops.
The standard approach that you can find everywhere, is a combination of erase with std::remove_it. You will find this construct in many many examples.
Please consider to use such a solution instead of a for loop.
You can even include the output in an algorithm using std::copy_if.
Please see:
#include <string>
#include <iostream>
#include <algorithm>
#include <iterator>
int main()
{
std::string test1{ "H23ey Th2e3re St01ack O34verflow" };
std::string test2{ test1 };
// C++ standard solution for erasing stuff from a container
test1.erase(std::remove_if(test1.begin(), test1.end(), ::isdigit), test1.end());
std::cout << test1 << "\n\n";
// All in one alternative
std::copy_if(test2.begin(), test2.end(), std::ostream_iterator<char>(std::cout), [](const char c) { return 0 == std::isdigit(c); });
return 0;
}
If there's two digits next to each other, it skips the second digit. This happens because the index, i, keeps going up, even though everything got shifted over:
for (size_t i {}; i < digalpha.size(); i++)
if (isdigit(digalpha.at(i)))
digalpha.erase(i,1); //Here, i goes up anyway, skipping character after digit
To fix this, we just have to decriment i after erasing a digit:
for (size_t i {}; i < digalpha.size(); i++) {
if (isdigit(digalpha.at(i))) {
digalpha.erase(i,1);
i--;
}
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am learning C++ and I have a problem with my program. It should print out following if n=11:
*---------*
-*-------*-
--*-----*--
---*---*---
----*-*----
-----*-----
----*-*----
---*---*---
--*-----*--
-*-------*-
*---------*
This is my code, which works correctly with n=5, but not with greater numbers:
#include <iostream>
using namespace std;
int main ()
{
int n;
cout << "Enter size (n x n): " << endl;
cin >> n;
for (int i=0;i<n;i++){
for (int j=0;j<n;j++){
if (i%n==j%n) cout << '*';
else if (i%(n-i)==j%(n-j)) cout << '*';
else cout << '-';
}
cout << endl;
}
return 0;
}
This is being printed out if n=11:
*---------*
-*----*--*-
--*-----*--
---*---*---
----*------
-----*-----
-*----*--*-
---*---*---
--*-----*--
-*----*--*-
*---------*
I see that I have successfully wrote how to print out one of '*' diagnoles. But something isn't working with other one, which is going backwards.
Unfortunately, I am not being able to resolve this problem and need your advice. What am I doing wrong? How to debug such problems?
This problem is really simple to debug.
Take a look at the first erroneous *. It appears at the position with i=1, j=6. With n=11, your condition i%(n-i)==j%(n-j) becomes 1%(11-1) == 6%(11-6) which is effectively true because the expression evaluates to 1 on both sides.
What is behind this expression? Why do you use this kind of if to determine whether the cell belongs to the second diagonal? Try to write down each pair i, j which should be printed on the second diagonal, and you should notice a more simple pattern.
P.S. In the expression if (i%n==j%n) you don't have to take operands modulo n, because both of them are less than n, so it is redundant and may be rewritten simply as if (i == j).
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am trying to solve this problem:
Write a program to count how many times each distinct word appears in its input.
This is the code so far:
#include <algorithm>
#include <iomanip>
#include <ios>
#include <iostream>
#include <string>
#include <vector>
#include <iterator>
using std::cin;
using std::sort;
using std::cout;
using std::streamsize;
using std::endl;
using std::string;
using std::setprecision;
using std::vector;
int main()
{
cout << "Enter words: ";
vector<string> lista;
vector<string> listaCitita;
string x;
while (cin >> x)
{
lista.push_back(x);
}
int listaSize = lista.size();
for (int i = 0; i <= listaSize -1; i++)
{
int x = 0;
int counter = 0;
vector<string>::iterator it = find(listaCitita.begin(), listaCitita.end(), lista[i]);
vector<string>::iterator itu = find(lista.begin(), lista.end(), lista[i]);
if (it != listaCitita.end())
{
break;
}
while(x <= listaSize -1)
{
if(lista[i] == lista[x])
{
counter++;
x++;
if(itu != lista.end())
{
}
else
{
listaCitita.push_back(lista[i]);
}
}
else
{
x++;
}
}
cout << "The string: '" << lista[i] << "' appeared " << counter << " times" << endl;
}
return 0;
}
I'm trying to: If the it variable has already been printed how many times the word showed, and it wouldn't be printed again how many times it showed.
That's why I made a second vector (listaCitita) where I add the elements that have already been iterated through. The problem is that it doesn't break out of the for loop when I do this.
if (it != listaCitita.end())
{
break;
}
The break statement ends execution of the nearest enclosing loop or conditional statement in which it appears. Control passes to the statement that follows the end of the statement, if any.
When you reach break, you will jump at the end of the for loop (return 0). What you want to use here is the continue keyword, which will skip the current word and continue with the next one.
If your program reaches break it will definitely break out of it.
One other way to break out of a loop especially if it is a nested loop and you want to break out of an outer loop would be goto.
...
while(...) { while(...) { if(...) { goto end; }}}
end: //will jump here
...
You can break out of nested loops using goto, throw or return (of course you need to separate your loops into a function or a lambda for this latter method to work).
In any case your particular task doesn't call for breaking out of a nested loop, or any other loop for that matter. You need to check if the word was already printed in the outer loop. If it was, continue, otherwise proceed to counting it, printing it, and pushing it to the vector of already-printed words.
Using containers and/or algorithms appropriate for the task would eliminate the need to use nested loops altogether. Consider std::unordered_map. Also read about std::count.