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 8 years ago.
Improve this question
I'm trying to create a program that intakes a string of characters, verifies it, then sorts it and prints it out.
I'm sure there is a glaring logic error in here somewhere, can someone help point it out? I've spent hours staring at my screen. I tried everything I know in my limited knowledge of C++, but I still can't get the thing working.
Anything you can offer will help me in some way, even if it's condescending.
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
void mySort(string &s);
int main()
{
string str;
char c;
bool invalid = true;
cout<<"Please enter some alphabetical characters:"<<endl;
cout<<"(* to end input): ";
do
{
getline(cin, str, '*');
for(int i = 0; i < str.length(); i++)
{
c = str.at(i);
}
if(! ( ( c >= 'a' && c <= 'z' ) || ( c >= 'A' && c <= 'Z' ) ) )
{
cout<<"Error!"<<endl;
}
else
{
(invalid==false);
cout<<"You entered: "<<str<<endl;
mySort(str);
}
} while(invalid==true);
system("PAUSE");
return(0);
}
void mySort(string &s)
{
sort(s.begin(), s.end());
cout<<"The string after sorting is: "<<s<<endl;
}
I'm almost sure the problem with the verification lies in this line:
if(! ( ( c >= 'a' && c <= 'z' ) || ( c >= 'A' && c <= 'Z' ) ) )
I'm sure my bools are wrong as well.
Anything, anything at all, I've wasted several hours of my life banging my head against the wall because of this.
You never set invalid to anything but true.
This line:
(invalid==false);
should be:
invalid = false;
The former version compares invalid to false, then throws away the result of the comparison. Nothing changes.
(invalid==false); Should be invalid=false;
First change:
(invalid == false);
invalid = false;
As others have said, you are not assigning the invalid variable correctly. You are also not validating the input string correctly, either. You loop through the entire string, and then validate only the last character seen, rather than validating each character while looping.
I would suggest re-writing the loop to get rid of the invalid variable and fix the validation, eg:
int main()
{
string str;
char c;
do
{
cout << "Please enter some alphabetical characters:" << endl;
cout << "(* to end input): ";
if (!getline(cin, str, '*'))
break;
if (str.empty())
cout << "You did not enter anything!" << endl;
else if (str.find_first_not_of("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") != string::npos)
cout << "Error! Bad input" << endl;
else
{
cout << "You entered: " << str << endl;
mySort(str);
break;
}
}
}
while (true);
system("PAUSE");
return 0;
}
Related
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 4 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
string word;
int l,eFound,xFound;
l = word.size();
cout <<"Enter a word: ";
cin >> word;
for (l>0 ; word.at(l)!='x' || word.at(l)!='e'; l--)
if (word.at(l) == 'e'){
eFound = true;
}
else if (word.at(l) == 'x'){
xFound = true;
}
if (eFound == true && xFound == true){
cout << "Your word, "<<word<<", contains the character 'e'"<<"\n";
cout << "Your word, "<<word<<", contains the character 'x'";
}
if (eFound == true && xFound != true){
cout << "Your word, "<<word<<", contains the character 'e'";
}
if (xFound == true && eFound != true){
cout << "Your word, "<<word<<", contains the character 'x'";
}
I'm not sure what is going on I'm trying to use a for loop to detect either e or x in a input of some word. I've clicked on other pages with the same error but they have different codes and I don't really understand what is explained. So what is causing this error? I'm 2 weeks into my first programming class, sorry if I'm asking a dumb question.
The issue is that indexing of std::string starts from zero. Not from 1. So, word.at(l) will crash if l = word.size();.
You should change the statement to: l = word.size() - 1;.
Also, Change your loop condition to for (; l >= 0 ; l--)
Suggestion:
Please go for library functions:
Like this:
#include <iostream>
#include <string>
using namespace std;
int main() {
string word;
cout <<"Enter a word: ";
cin >> word;
bool eFound = word.find('e') != string::npos;
bool xFound = word.find('x') != string::npos;
if (eFound) {
cout << "Your word, "<<word<<", contains the character 'e'" << "\n";
}
if (xFound) {
cout << "Your word, "<<word<<", contains the character 'x'" << "\n";
}
return 0;
}
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 4 years ago.
Improve this question
I seem to be looping through my array wrong, I've got it set up to prompt the user for a list of numbers and I am supposed to be comparing it to another number that the user sets.
#include <iostream>
using namespace std;
bool chk = true;
int main() {
/*
Write a program that asks the user to type 10 integers of an array and an integer s.
Then search the value s from the array and display the value of s if it is found in
the array otherwise print sorry not found..
*/
int userArray[10], i, greater = 0;
int s;
cout << "Enter a check number: \n";
cin >> s;
if (chk = true) {
//prompt for array list
for (i = 0; i < 9; i++) {
if (i == 0) {
cout << "Enter ten numbers: " << "\n";
cin >> userArray[i];
}
else {
cin >> userArray[i];
}
chk = false;
}
//loop through the array
for (int i = 0; i <= 10; i++) {
if (s = userArray[i]) {
//for testing
cout << userArray[i];
//cout << s;
}
else {
cout << "No match found!";
}
//I was just using this to pause the console and let me inspect result
cin >> greater;
return 0;
}
}
}
I assume the following code is where the problem lies. The idea is i set s = 2 enter in a list of numbers and then compare to s and print s if there is a match if not I print No match found. When I enter in a number that i know matches s it seems to print the first number in the array, but i thought since I loop through the numbers one by one in the for loop that it should display when it reaches the right number not when it stops. Thanks in advance
//loop through the array
for (int i = 0; i <= 10; i++) {
if (s = userArray[i]) {
//for testing
cout << userArray[i];
//cout << s;
}
else {
cout << "No match found!";
}
You are using a single equals sign. This is setting s to userArray[i] so it always evaluates to true. For comparisons, use double equal signs, like this:
if (s == userArray[i]) {...}
Also, your return statement is inside your loop (credit to #UnholySheep).
you are comparing with a single assignment operator = you should be using the equal operator instead ==
if (s = userArray[i]) with in the for loop is one example.
you also doing the same mistake in
if (chk = true)
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 6 years ago.
Improve this question
#include <iostream>
using namespace std;
int countLetters(char text[], char letter);
int main()
{
char letter;
cout << "Enter a letter: ";
cin >> letter;
cin.ignore();
char text[1024];
cout << "Enter text: ";
cin.getline(text, 1024);
int letterCount = countLetters(text, letter);
cout << "Number of '" << letter << "'s: " << letterCount << endl;
return 0;
}
int countLetters(char text[], char letter)
{
int letterCount = 0;
for (int i = 0; i <= text[i]; i++)
{
if (letter == text[i])
letterCount++;
}
return letterCount;
}
This code, as written, is designed to ask the user for, first, the letter they want to search for in a line of text. Second, it will ask the user to input the line of text they want to have searched. Finally, it will spit out how many letters there are in the specific line of text they input.
My specific error lies here: when user asks for 'e' in "CS 124 - Introduction to Software Development", program only declares that there is one 'e' . I'm unsure what's wrong, because when you run the program and input 'o' while asking to search the exact same line of text, you get the proper number of 'o' values returned, 4.
Any ideas as to what my error is and why it glitches when searching for 'e' ?
Your for condition is wrong, the for loop should continue while i is less than text's length not the value of text[i]. Since this is C++ you should use strings not character arrays, why make it harder on yourself?
The code below is a C++ approach, note that my C++ is a bit rusty and the code might contain errors.
#include <iostream>
#include <string>
using namespace std;
int countLetters(string text, char letter);
int main() {
char letter = ' ';
string text;
cout << "Enter a letter: ";
cin >> letter;
cin.ignore();
cout << "Enter text: ";
getline(cin, text); // use 'getline(cin, text)' instead of 'cin >> text'
int letterCount = countLetters(text, letter);
cout << "Number of '" << letter << "'s: " << letterCount << endl;
return 0;
}
int countLetters(string text, char letter) {
int letterCount = 0;
for (int i = 0; i < text.size(); i++) {
if (letter == text[i]) {
letterCount += 1;
}
}
return letterCount;
}
change the condction
i <= text[i]
to
text[i] != '\0'
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 8 years ago.
Improve this question
I'm quite new to c++ so please understand that my question may be silly.
I need to create a function which takes from the user a table and fills it with only specific characters. Let's say that the user needs to input his name. If the user inputs a charater from A to Z (or a to z) the character should be displayed on the screen and in that case- everything is fine. The problem is- when the user inputs a forbidden character (for instance 1-9) this shouldn't be displayed on the screen and the cursor should stay in the same position).
Do you guys know how to do this?
May be you can use this to do your job:
char ch;
while(ch = getch())
{
if((ch>='A' && ch<='Z') || (ch>='a' && ch<='z'))
{
cout << ch;
}
}
This will print only [A-Z][a-z]. You can also store your required char to use further.
On Windows you can use conio.h.
Also, you can overload the istream::operator>> function to make solution more elegant and easy to use:
Complete example:
#include <iostream>
#include <conio.h>
using namespace std;
struct person_t
{
string name;
string last_name;
};
// This is the function you're looking for.
void get_filtered_string(string &str)
{
char c;
str = "";
do
{
c = _getch();
if (('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z'))
{
putchar(c); // 1
str.push_back(c);
}
} while (c != '\r'); // 2
}
istream &operator>>(istream &stream, person_t &person)
{
string str = "";
cout << "Enter name: ";
get_filtered_string(str);
person.name = str;
cout << endl;
cout << "Enter last name: ";
get_filtered_string(str);
person.last_name = str;
cout << endl;
return stream;
}
int main()
{
person_t person;
cin >> person;
cout << person.name.c_str() << " " << person.last_name.c_str() << endl;
return 0;
}
Output character to screen.
In Windows when you hit Enter you're introducing two characters '\r' and '\n' in that order. Thats why we check here for '\r'.
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 9 years ago.
Improve this question
I am trying to make a little program that will ask the user if they're human and then do a bunch of other stuff afterwards. The following is a snippet of the code where the user is asked whether they're human. Now if you enter anything other than yes or no, the program then loops with the 'goto' statement. The problem that I'm having is that the if statements, when they end go to this 'goto' statement thus looping when the program should end. How can I get the goto statement to be exclusively part of the second else if statement? Failing that, is there another loop structure that I should use? Any help would be greatly appreciated.
#include <iostream>
#include <windows.h>
#include <string>
using namespace std;
int main ()
{
go:
string i;
cout << "Are you Human?>"<<endl;
cin >> i;
if (i == "yes"&&"Yes")
cout<< "Cool"<<endl;
else if (i == "no"&&"No")
cout<< "Interesting"<<endl;
else if (i!= "yes"&&"Yes"&&"no"&&"No")
cout<< "A simple Yes or No will suffice..."<<endl;
goto go;
system("pause");
return 0;
}
You really need to learn how to write if-conditions in C++. For example, you need to change
if (i == "yes"&&"Yes")
to
if (i=="yes" || i=="Yes")
to be able to check i is yes or Yes. And change others accordingly.
You need to use braces to define scopes instead of just code indentation (this is just for you, not for compiler). For example,
else if (... ...)
{
cout<< "A simple Yes or No will suffice..."<<endl;
goto go;
}
You have to place the goto statement in the code block of this else-if.
else if (i!= "yes"&&"Yes"&&"no"&&"No")
{
cout<< "A simple Yes or No will suffice..."<<endl;
goto go;
}
Also take into account that conditions as
else if (i!= "yes"&&"Yes"&&"no"&&"No")
or
if (i == "yes"&&"Yes")
are invalid, In fact the last condition is equiavelnt to
if ( ( i == "yes" ) && ( "Yes" ) )
as "Yes" is implicitly converted to pointer to its first character then expression "Yes" will be always equal to true and the condition is equivalent to
if ( i == "yes" )
Also it is a very bad idea in general to use goto statement. You should forget that there is goto statement in C/C++. Instead you should use control structures as while or do-while.
For example
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
int main ()
{
string s;
do
{
cout << "Are you Human?>" < <endl;
cin >> s;
bool answer;
if ( answer = ( s == "yes" || s == "Yes" ) )
cout << "Cool" << endl;
else if ( answer = ( s == "no" || s == "No" ) )
cout << "Interesting" << endl;
else
cout << "A simple Yes or No will suffice..." << endl;
} while ( !answer );
system( "pause" );
return 0;
}
if you want to accept "yes" or "Yes" you should write condition like this:
if (i=="yes" || i=="Yes")
But better solution is make string's letters same case (lower or upper) and then compare it.
int main ()
{
go:
string i;
while(1)
{
cout << "Are you Human?>"<<endl;
cin >> i;
if (i == "yes"|| i == "Yes")
cout<< "Cool"<<endl;
else if (i == "no"|| i == "No")
cout<< "Interesting"<<endl;
else
{
cout<< "A simple Yes or No will suffice..."<<endl;
break;
}
}
system("pause");
return 0;
}
Don't forget that if you don't put curly braces after the statements, only the following statement is to be executed.