Counting characters in a string - c++

My code runs and works well the first time around, but I am having looping problems:
My code isn't counting characters that are in words
The second time around when you press "yes," it ends up printing everything out. I must have a loop in the wrong spot, but I can't find it for the life of me.
#include <string>
#include <fstream>
#include <iostream>
#include <algorithm>
#include <iterator>
using namespace std;
int main()
{
char character;
string sentence;
char answer;
int cCount;
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: ";
cin >> sentence;
if(character == '\n' || sentence.empty())
{
cout << "Please enter a valid answer:\n";
break;
}
else {
cCount = count(sentence.begin(), sentence.end(), character);
cout << "Your sentence had" << " " << cCount << " " << character << " " << "character(s)" << '\n';
}
cout << "Do you wish to enter another sentence (y/n)?: \n";
cin >> answer;
if (answer == 'n'){
break;
}
}
return 0;
}

By just reading your code, it looks fine, except where you get the sentence. Using cin, it will only read until it sees a newline or a space, so if you're entering a sentence, it will read every word as a different input.
Try getline(cin, sentence) and see if that fixes the problem.
Edit: Forgot to add in: use cin.ignore() after the getline. cin reads up to, and including the line break (or space) while getline only reads up to the line break, so the line break is still in the buffer.

use
cin.ignore(); //dont forget to use cin.ignore() as it will clear all previous cin
getline(cin, sentence, '\n'); //take the sentence upto \n i.e entered is pressed

You don't have the loops wrong. What's wrong is that you are assuming that
cin >> sentence;
does something different from what it really does.
If you want to read a line of text, then do this
getline(cin, sentnence);
Your code reads a single word only.

use cin it will end with a newline or a space
eg:
when you input hello world it will get hello
and you can try
getline
it wiil end with a newline

This is working, try this.
#include <string>
#include <fstream>
#include <iostream>
#include <algorithm>
#include <iterator>
using namespace std;
int main()
{
char character;
string sentence;
char answer;
int cCount;
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: ";
fflush(stdin);
getline(cin, sentence, '\n');
if(character == '\n' || sentence.empty())
{
cout << "Please enter a valid answer:\n";
break;
}
else {
cCount = count(sentence.begin(), sentence.end(), character);
cout << "Your sentence had" << " " << cCount << " " << character << " " << "character(s)" << '\n';
}
cout << "Do you wish to enter another sentence (y/n)?: \n";
cin >> answer;
if (answer == 'n'){
break;
}
}
return 0;
}
after you enter first input and enter that enter is considered as input in sentence
So, you need to flush that and after that you can scan that sentence.

Try:
cCount = count(sentence.c_str(), sentence.c_str()+sentence.length(), character);

Related

std::cin skips white spaces

So I am trying to write a function to check whether a word is in a sentence, by looping through a char array and checking for the same string of char's. The program works as long as the Sentence doesn't have any spaces. I googled around and they are all the same suggestions;
cin.getline
But however I implement it, it either doesn't run or skips the entire input and goes straight towards the output.
How can I account for spaces?
#include <iostream>
using namespace std;
bool isPartOf(char *, char *);
int main()
{
char* Word= new char[40];
char* Sentence= new char[200];
cout << "Please enter a word: ";
cin >> Word;
cout << endl << "Please enter a sentence: ";
//After Word is input, the below input is skipped and a final output is given.
cin.getline(Sentence, 190);
cout << endl;
if (isPartOf(Word, Sentence)==true)
{
cout << endl << "It is part of it.";
}
else
{
cout << endl << "It is not part of it.";
}
}
bool isPartOf(char* a, char* b) //This is the function that does the comparison.
{
int i,j,k;
for(i = 0; b[i] != '\0'; i++)
{
j = 0;
if (a[j] == b[i])
{
k = i;
while (a[j] == b[k])
{
j++;
k++;
return 1;
if (a[j]=='\0')
{
break;
}
}
}
}
return 0;
}
And I am not allowed to use strstr for the comparison.
Ok, I'll try to explain your problem:
Let's assume this is your input:
thisisaword
this is a sentence
When you use cin and give it any input, it stops at the newline character which in my example follows character 'd' in 'thisisaword'.
Now, your getline function will read every character until it stops newline character.
Problem is, the first character getline encounters is already a newline so it stops immediately.
How is this happening?
I'll try to explain it like this:
If this is your input given to a program (note \n characters, treat it like a single character):
thisisaword\n
this is a sentence\n
What your cin function will take and leave:
\n
this is a sentence\n
Now getline sees this input and is instructed to get every character until it meets a newline character which is "\n"
\n <- Uh oh, thats the first character it encounters!
this is a sentence\n
cin reads input and leaves "\n", where getline includes "\n".
To overcome this:
\n <- we need to get rid of this so getline can work
this is a sentence\n
As said, we cannot use cin again because it will do nothing.
We can either use cin.ignore() without any parameters and let it delete first character from input or use 2x getline(first will take remaining \n, second will take the sentence with \n)
You can also avoid this kind of problem switching your cin >> Word; to a getline function.
Since this is tagged as C++ I changed Char*[] to Strings for this example:
string Word, Sentence;
cout << "Please enter a word: "; cin >> Word;
cout << endl << Word;
cin.ignore();
cout << "\nPlease enter a sentence: "; getline(cin, Sentence);
cout << endl << Sentence;
OR
string Word, Sentence;
cout << "Please enter a word: "; getline(cin, Word);
cout << endl << Word;
cout << "\nPlease enter a sentence: "; getline(cin, Sentence);
cout << endl << Sentence;
How about using this:
std::cin >> std::noskipws >> a >> b >> c;
cin by default utilizes something like this:
std::cin >> std::skipws >> a >> b >> c;
And you can combine flags:
std::cin >> std::skipws >> a >> std::noskipws >> b;
Tell me if it works for you : )
By default operator>> skips whitespaces. You can modify that behavior.
is.unsetf(ios_base::skipws)
will cause is's >> operator to treat whitespace characters as ordinary characters.

Using cin.get() to discard unwanted characters from the input stream in c++

I am working on an assignment for my C++ class. The following code is given. The directions explain to enter a six character string and observe the results. When I do this, the second user prompt is passed over and the program ends. I am pretty certain the reason for this is that the first cin.getline() is leaving the extra character(s) in the input stream which is messing up the second cin.getline() occurrence. I am to use cin.get, a loop, or both to prevent the extra string characters from interfering with the second cin.getline() function.
Any tips?
#include <iostream>
using namespace std;
int main()
{
char buffer[6];
cout << "Enter five character string: ";
cin.getline(buffer, 6);
cout << endl << endl;
cout << "The string you entered was " << buffer << endl;
cout << "Enter another five character string: ";
cin.getline(buffer, 6);
cout << endl << endl;
cout << "The string you entered was " << buffer << endl;
return 0;
}
You are right. The newline character stays in the input buffer after the first input.
After the first read try to insert:
cin.ignore(); // to ignore the newline character
or better still:
//discards all input in the standard input stream up to and including the first newline.
cin.ignore(numeric_limits<streamsize>::max(), '\n');
You will have to #include <limits> header for this.
EDIT:
Although using std::string would be much better, following modified code works:
#include <iostream>
#include <limits>
using namespace std;
int main()
{
char buffer[6];
cout << "Enter five character string: ";
for (int i = 0; i < 5; i++)
cin.get(buffer[i]);
buffer[5] = '\0';
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << endl << endl;
cout << "The string you entered was " << buffer << endl;
cout << "Enter another five character string: ";
for (int i = 0; i < 5; i++)
cin.get(buffer[i]);
buffer[5] = '\0';
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << endl << endl;
cout << "The string you entered was " << buffer << endl;
return 0;
}

Can't get char from cin.get()

I'm working through some beginner exercises on c++, and this has me stumped. I can enter a number, but I don't get the option to enter a character afterwards, and it skips to the final line.
I know I can use cin >> symbol, but i would like to know why this isn't working.
#include<iostream>
using namespace std;
int main() {
cout << "Enter a number:\n";
int number;
cin >> number;
char symbol;
cout << "Enter a letter:\n";
cin.get(symbol);
cout << number << " " << symbol << endl;
return 0;
}
You should remove '\n' from stream, remained after entering the number:
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
Without it you will read newline character. You could check that with:
std::cout << (symbol == '\n') << std::endl;
\n will remain in the buffer after the first cin. You can solve this problem by adding an empty cin.get() between two consecutive reads.
cin.get(string1,maxsize);
cin.get();
cin.get(string2,maxsize);
Or you can use fflush:
cin.get(string1,maxsize);
fflush(stdin);
cin.get(string2,maxsize);

Using a space for canceling a simple loop

Here is my code for this simple assignment:
Write the code that will read character input from the user until a blank (a space) is entered. Print how many characters were entered. Keep in mind the user may decide to enter a blank as his first character.
Why is the space not ending the loop?
#include <iostream>
using namespace std;
int main(){
char answer;
int count=1;
do{
cout << "please enter number " << count;
cin >> answer;
count++;
}while(answer!=' ');
cout << "you entered " << count-1 << "numbers." << endl;
return 0;
}
The cin >> operations skip all kinds of whitespace by default. You can use cin >> noskipws; before your loop to disable whitespace skipping or use cin.get() instead:
cin.get(answer);
You should be aware that newlines and carriage returns are no longer skipped now, so you have to handle them separately. Also, you should check the stream status to react to end-of-file:
do {
cout << "Please enter number " << count << endl;
do {
cin.get(answer);
} while (cin && (answer == '\r' || answer == '\n'));
count++;
} while (cin && answer != ' ');

program skipping a line of code

I have been working on this program for a while and I finally got rid of the compile errors. But when I tried it, the program basically skipped a line of code.
#include <iostream>
#include <cstdlib>
#include <cstring>
using namespace std;
int main(){
string nameOfFile = "";
char index;
char title[100];
char name[100];
char copyright[100];
cout << "Welcome, and hello to the html templating software" << endl;
cout << "Is this your index page?\ny/n" << endl;
cin >> index;
if (index=='n'){
cout << "Enter the prefered name of this file" << endl;
getline(cin, nameOfFile, '\n');
}
cout << "What will the title of the page be?" << endl;
cin.getline(title, 100);
cout << "What is your name?" << endl;
cin.getline(name, 100);
cout << "What is the copyright?" << endl;
cin.getline(copyright, 100);
cin.get();
return 0;
}
You see how after asking if this is your index page it skips the next cin.getline function no matter the scenario.
When the user entered the index, they also typed a newline, but your cin didn't remove it from the input stream. So, your call to cin.getline returns immediately because of the leftover newline.
Add a call to cin.ignore before the cin.getline to flush it out.
replace getline(cin, nameOfFile, '\n')
with
cin >> nameOfFile