C++ count number of characters in a string - c++

I am so close, I need to count the number of given characters in a given string. It needs to loop over and over again but i keep getting this error:
countchar.cpp:27:22: error: â was not declared in this scope
countchar.cpp:27:38: error: â was not declared in this scope
countchar.cpp:27:61: error: â cannot be used as a function
I really am not too familiar with the algorith of count but if someone could help out, that would be appreciated. Here is my code:
#include <string>
#include <fstream>
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
char character;
string sentence;
char answer;
while(1) {
cout << "Enter a character to count the number of times it is in a sentence: ";
cin >> character;
cout << "Enter a sentence and to search for a specified character: ";
getline(cin, sentence);
if(character == '\n' || sentence.empty())
{
cout << "Please enter a valid answer:\n";
break;
}
else {
int count = count(begin(sentence), end(sentence), character);
cout << "Your sentence had" << count << character
<< "character(s)";
}
cout << "Do you wish to enter another sentence (y/n)?: ";
cin >> answer;
if (answer == 'n'){
break;
}
}
return 0;
}

The problem seems to be in this line:
int count = count(begin(sentence), end(sentence), character);
You declare a variable count and immediately after you use it as a function. You have to rename the variable (to, say, c) to use function std::count.
As for the remaining errors, you should use sentence.begin() instead of begin(sentence) and similarly sentence.end() instead of end(sentence).

Related

C++ Loop for String

I am struggling to create a loop for getting input from user. The input must push_back() each instance.
#include <iostream>
#include <array>
#include <cstring>
#include <vector>
#include <string>
#include <string.h>
using namespace std;
int main()
{
vector <string> bookQ = { "what","book","is","that","you","are","reading" };
for (int i = 0; i < bookQ.size(); i++) {
cout << bookQ[i] << ' ';
}
cout << endl;
string input;
int x = 0;
for (x != '1') { // require a loop to input string and end when user prompts
cout << "Enter 1 to stop" << endl; //
cin >> x; //
getline(cin, input); //
bookQ.push_back(input); //
} //
for (int i = 0; i < bookQ.size(); i++) {
cout << bookQ[i] << ' ';
}
cout << endl;
return 0;
}
Your for loop is missing the declaration and (iteration) expression parts:
for (declaration-or-expression; declaration-or-expression; expression)
so it should have looked like this:
for (;x != '1';) {
which is generally written as
while (x != '1') {
That would cause problems though since it would not stop directly when the user entered 1.
You are also comparing an int with a char ('1'), so in order to exit the loop, the user would have had to enter 49 (the ASCII value for 1), not 1.
You are also mixing formatted input (cin >> x) with unformatted input (getline). I suggest that you stick to one only.
Example:
while(cout << "Enter 1 to stop\n", getline(cin, input) && input != "1") {
bookQ.push_back(input);
}
Assuming you meant that input is a string, then you've made a few mistakes with types. First of all, you've used wrong type for variable x, you used int which is integer type, and the type string is required. Secondly, when comparing x with '1' you used single quotes, which define the type of variable as char, not string. To make 1 a string you should use double quotes, like so "1". Besides that, you have used for(condition), which is incorrect syntax. You should use while(condition). Also, when your loop iterates, the x variable is the input book name, and input variable is always an empty string, so I would suggest replace input with x everywhere. The working code is below.
P.S. I am not sure whether you want "1" to be in the final vector, so I haven't changed that
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main() {
vector<string> bookQ = {"what", "book", "is", "that", "you", "are", "reading"};
for (int i = 0; i < bookQ.size(); i++) {
cout << bookQ[i] << ' ';
}
cout << endl;
string input;
string x;
while (x != "1") {
cout << "Enter 1 to stop" << endl;
cin >> x;
bookQ.push_back(x);
}
for (int i = 0; i < bookQ.size(); i++) {
cout << bookQ[i] << ' ';
}
cout << endl;
return 0;
}
simply check if input is 1 everytime the user enters somthing, and when it does = 1, simply break loop.
string x;
while (true) { // require a loop to input string and end when user prompts
cout << "Enter 1 to stop" << endl;
cin >> x;
if (x == "1"){
break;
}
getline(cin, x);
bookQ.push_back(x);
}
}
First, your for syntax is wrong. You want a while loop instead, or in this case a do..while loop would make more sense. Also, you are pushing the user's input into the vector before validating what the input actually is.
Second, x is an integer, but '1' is a character whose ASCII value is number 49. Your loop will never end, because != will always be true. Since you want the user to enter number 1 to stop the loop, you need to drop the quotes:
Third, what is the point of pre-populating bookQ? Just declare the bookQ without any initial data, and then cout the entire question as a normal string. This way, after the user is done entering input, the vector will contain only the user's input and nothing else.
Try something more like this:
#include <iostream>
#include <vector>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
vector <string> bookQ;
string input;
cout << "what book is that you are reading" << endl;
do {
cout << "Enter a book, or 1 to stop" << endl;
getline(cin >> ws, input);
if (input == "1") break;
bookQ.push_back(input);
}
while (true);
for (size_t i = 0; i < bookQ.size(); ++i) {
cout << bookQ[i] << ' ';
}
cout << endl;
return 0;
}

Undefined behaviour when entering `char` for integer variable with `std::cin`

I have this while loop, just to check if the entered number is 2. If the user entered by accident a letter instead of a number the loop goes to infinity even though I've added isdigit, but didn't fix the loop from going crazy if the input is a character. This is code:
int num1;
bool cond {false};
while(!cond){
cout<<"enter 2:";
cin>>num1;
if (!isdigit(num1)){
cout<<"not a digit:";
cin>>num1;
}
//
if(num1 == 2)
cond = true;
}
I would suggest trying something a little more straightforward instead of your current code:
#include <iostream>
#include <limits>
using namespace std;
int main()
{
int num1;
cout << "Please enter the number 2:";
cin >> num1;
while (num1 != 2)
{
cin.clear(); //Clears the error flag on cin.
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "You did not enter the number 2, Please try again:";
cin >> num1;
}
return 0;
}
Now, cin.ignore(numeric_limits<streamsize>::max(), '\n'); is when it ignores up until '\n' or EOF \n is the delimiter meaning that, that is the character at which cin will stop ignoring.
Furthermore, numeric_limits<streamsize>::max() is basically saying there is no limit to the number of characters to ignore.
You need to use the header file #include<limits> to use this.
I recommend separating the reading of input data from converting it to a number. A good method for this is to use stringstream. Here's a working example:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
int num1;
string input;
bool cond{ false };
cout << "enter 2:";
while (!cond) {
getline(cin, input);
stringstream ss(input);
ss >> num1;
if( ss.fail() ){
cout << "not a digit:";
continue;
}
//
if (num1 == 2)
cond = true;
else
cout << "enter 2:";
}
return 0;
}
int num1;
bool cond {false};
do{
cout<<"enter 2:";
cin>>num1;
if (cin.good()) {
cond = true;
}else {
cin.clear();
cin.ignore();
cout << "Invalid, please enter 2." << endl;
}
}while(!cond);
While false, execute statements. Also, if you want the user to re-enter a number, cin must be flushed.
Try declaring the variable num1 as char because isdigit(ch) works for char and not for int.
I hope this solves your problem
Why does the loop iterate infinitely?
Let's take this example
int a;
std::cin >> a;
std::cout << "Entered: " << a;
Now let's test it with different inputs
with int
5
Entered: 5
10
Entered: 10
Yes just as we would expect, but what happens when you enter a char?
with char
r
Entered: 0
f
Entered: 0
Why does this happen?
When you declare the variable int, and then do std::cin >> , you are telling the input method that the user will enter an integer, but when it doesn't get what it expected, it will fail. C++ will not implicitly convert the value of char into int. Hence, you get strange results.
How to solve this?
As I have mentioned earlier, it fails. When this fails you can catch it this way
if (!(std::cin >> a))
{
std::cout << "Invalid input ! \n";
}
We're saying, if the input fails, show the message.
let's test this new code.
int a;
if (!(std::cin >> a))
{
std::cout << "Invalid input !\n";
}
else
{
std::cout << "Entered: " << a;
}
5
Entered: 5
r
Invalid input !
How to print char value of the int?
If you want to just print the ASCII value of the entered number, you need to cast the value into char.
You can do
int num = 48;
char character_value = num;
Here C++ will implicitly convert char into int.
But if you need a safer type of conversion, prefer using static_cast<>.
The syntax looks like this
int a = 5;
char character_value = static_cast<char>(a);
Static cast in C++
Type casting in C++
Dealing with invalid input in C++

C++ Debug Assertion Failed, Invalid Null Pointer

I've looked everywhere, but I cannot find a solution to exactly why this happens in my situation.
I'm making a simple string function that asks for a string, and prints out the length.
However, I get an "Invalid Null Pointer" assertion error when I run the compiled version. I have had no errors when compiling, but the error comes up when I run it.
This is the function causing the problem:
string getString()
{
string wordInput;
cout << "Enter a word that has AT LEAST four (4) letters! ";
getline(cin, wordInput);
while (wordInput.length() <= 3)
{
cout << "Enter a word that has AT LEAST four (4) letters! ";
getline(cin, wordInput);
}
return 0;
}
The while loop isn't a problem. I commented it out and I still got the same error. How is initializing word input, cout, and getline giving me the error?
Here is my whole code so far (not finished). I tried running the string by itself too, the getKeyLetter function isn't a problem.
#include <iostream>
#include <string>
#include <cassert>
using namespace std;
char getKeyLetter()
{
char keyLetter;
string convertFromString;
cout << "Enter a SINGLE character! ";
getline(cin, convertFromString);
while (convertFromString.length() > 1)
{
cout << "Enter a SINGLE character! ";
getline(cin, convertFromString);
}
assert(convertFromString.size() == 1);
keyLetter = convertFromString[0];
return 0;
}
string getString()
{
string wordInput;
cout << "Enter a word that has AT LEAST four (4) letters! ";
getline(cin, wordInput);
while (wordInput.length() <= 3)
{
cout << "Enter a word that has AT LEAST four (4) letters! ";
getline(cin, wordInput);
}
return 0;
}
int main()
{
getKeyLetter();
getString();
return 0;
}
First, in your GetKeyChar() function, writing:
char ch;
cout << "Enter a single character: ";
cin >> ch;
will give you the first character the person types into the command prompt. So, typing "check" will have ch = c.
Second, as eran said, at the end of your functions, you have
return 0;
Unless you want both functions to return a char and string respectively, make them void GetKeyLetter() and void GetString(). Or, if you do want to return something, have them return ch (from my example) and return wordInput.
Only int main(), per standard, needs return 0, to show you that it exited correctly. the variable type you put in front of your functions is what variable you plan on returning. 0 is an int, so that's what it returns based on convention. As was pointed out, a return is not necessary in main. If you want your functions to return values, do this in your main.
string str;
char ch;
ch = GetKeyLetter();
str = GetString();
return 0;
And have your functions return the char and string value you want them to.

Testing for an integer in c++

I'm trying to write a c++ program that tests each input integer, and stops if the input is invalid.
Here is my code, without the testing part:
#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
int i;
do
{
cout << "\nPlease enter an integer: ";
cin >> i;
cout << endl << i << endl;
} while(i != 0);
system("Pause");
return 0;
}
How can I test the input for validity?
The easiest is to use std::getline to read a whole line of input into a std::string, and then test whether that string is a valid integer specification.
It's also possible to do this by testing the failure state of cin, and clearing it, but that way lies an assortment of complications that you don't want.
In order to test the string you can use a high level std::istringstream (just read from it and test its failure state after) or, more efficient but a little more complicated, strtol from the C library (the latter is what a C++ stream uses internally).
You need to test whether a string is an integer without crashing.
You can do this with strtol(). It converts the string to an integer, and reports on the first character that is not a legal char for a number. No invalid characters means the entire string was an integer.
There is a good description and example of how to use it here:
http://www.tutorialspoint.com/c_standard_library/c_function_strtol.htm
#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
int i;
do
{
cout << "\nPlease enter an integer: ";
while(!(cin >> i))
{
cin.clear();
cin.ignore();
cout << "\nInput was invalid, please re-enter: ";
}
cout << endl << "The integer is: " << i << endl;
} while(i != 0);
system("Pause");
return 0;
}

Recognize "010" and similar numbers as a palindrome using modulus in C++

First post! This is my second semester with "Advanced C & C++" so any help is GREATLY appreciated. I've already scoured as much of stackoverflow and a few other resources to try and help me understand what I'm doing (or not doing) with this slew of logically inept code.
The goal of this program is to recognize whether or not a 'number' given by the user is a palindrome. Sounds simple enough right?! Ugh...well this is what I have been stuck on:
#include <iostream>
using std::cout;
using std::cin;
#include <string>
using std::string;
#include <cstdlib>
int main()
{
//variable declarations
string buffer;
//user input
cout << "Enter a number to see if it is a palindrome[Q to quit]: ";
getline(cin, buffer);
//looooop
while(buffer != "Q" && buffer !="q")
{
int userNum, length, sum = 0, temp;
userNum = atoi(buffer.c_str());
for(temp = userNum; userNum !=0; userNum=userNum/10)
{
length = userNum % 10;
sum = sum*10+length;
}
if(temp==sum)
cout << temp << " is a palindrome!!\n\n";
else
cout << buffer << " is NOT a palindrome!\n\n";
cout << "Enter a number to see if it is a palindrome[Q to quit]: ";
getline(cin, buffer);
}
}
The problem arises when input of "010", or "400" is given. "400" is essentially "00400" in this case and both should be seen as a palindrome.
A better approach would be to get trailing zeros for the given number as below:
int noOfTrailingZeros = str.length;
while(str[--noOfTrailingZeros]=='0');
noOfTrailingZeros = str.length - noOfTrailingZeros;
Or the integer way as:
int noOfTrailingZeros = str.length;
while(num%10==0)
{
noOfTrailingZeros++;
num/=10;
}
Now, check for the input string whether it has the same number of zeros befire the number or not as:
int counterZeros = 0;
while(str[counterZeros++]=='0');
check these 2 numbers and if trailing zeros are more than the zeros at beginning, add that many at the beginning and pass that string to palindrome function.
First of all, to recognize a palindrome, you don't have to do atoi. Just pass from the start to the middle checking if
buffer[i] == buffer[length - i]
Second, use the atoi to make sure it is a number and you're done.
Other way is to compare the string with itself reversed:
string input;
cout << "Please enter a string: ";
cin >> input;
if (input == string(input.rbegin(), input.rend())) {
cout << input << " is a palindrome";
}