#include <iostream>
using namespace std;
int main()
{
string sentence;
int countv = 0, countc = 0, countspace = 0, number, s = 1;
cout << "How many sentence would you like to check? - ";
cin >> number;
while(s <= number)
{
cout << "\nSentence " << s << ":";
cin.ignore();
getline(cin, sentence);
for(int i = 0; i < sentence.length(); i++)
{
if(sentence[i] == 'a' || sentence[i] == 'e' || sentence[i] == 'i' || sentence[i] == 'o' || sentence[i] == 'u')
countv++;
else if(isspace(sentence[i]))
countspace++;
else
countc++;
}
cout << "\nSentence " << s << " result:";
cout << "\nThere are " << countv << " vowels in the sentence.";
cout << "\nThere are " << countc << " consonants in the sentence.";
cout << "\nThere are " << countspace << " whitespace in the sentence.";
countc = 0, countv = 0, countspace = 0;
s++;
cout << "\n";
}
}
I'm trying to count the number of vowels and consonants in multiple strings but, for some reason, it only gives the correct output for the first string.
I've noticed that, for the next strings (2nd, 3rd and so on), it does not count the first letter of the string. Why is this?
The code is ignoring the first character of each of the strings after the first because you are telling it to ignore those on input … with the call to cin.ignore(). That call should not be inside the loop but immediately before it, so as to ignore the newline that is left in the input stream after the cin >> number extraction.
Note that the call to getline does not leave that newline in the stream's buffer; see this cppreference page:
… the next available input character is delim, as tested by
Traits::eq(c, delim), in which case the delimiter character is
extracted from input, but is not appended to str.
Here's a suitably modified version of your code:
#include <string>
#include <iostream>
using std::cin, std::cout;
int main()
{
std::string sentence;
int countv = 0, countc = 0, countspace = 0, number, s = 1;
cout << "How many sentence would you like to check? - ";
cin >> number;
cin.ignore(); // Call ignore HERE (once) to skip the newline left in the buffer from the above!
while (s <= number)
{
cout << "\nSentence " << s << ":";
// cin.ignore(); WRONG!
std::getline(cin, sentence);
for (size_t i = 0; i < sentence.length(); i++)
{
if (sentence[i] == 'a' || sentence[i] == 'e' || sentence[i] == 'i' || sentence[i] == 'o' || sentence[i] == 'u')
countv++;
else if (isspace(sentence[i]))
countspace++;
else
countc++;
}
cout << "\nSentence " << s << " result:";
cout << "\nThere are " << countv << " vowels in the sentence.";
cout << "\nThere are " << countc << " consonants in the sentence.";
cout << "\nThere are " << countspace << " whitespace in the sentence.";
countc = countv = countspace = 0; // Nicer than the dodgy use of the comma!
s++;
cout << "\n";
}
}
Related
I want to reverse the input string; this is the code I wrote, but I am unable to print the reverse of the string.
#include<iostream>
using namespace std;
void main() {
char Title[] = "\t THE ANALYZER";
char phrase[501];
int charTotal = 0;
int numTotal = 0;
int letterTotal = 0;
int vowelTotal = 0;
int consonTotal = 0;
int spacesTotal = 0;
int specialCharTotal = 0;
cout << Title<< endl;
cout << "\t ____________" << endl;
cout << " Enter your phrase (Max 500): ";
cin.getline(phrase, 501);
cout << " Thanks, Analyzing..." << endl;
cout << " These are the informations about your phrase" << endl;
for (int i = 0; phrase[i] != '\0' ; i += 1) {
if (phrase[i] != '\0') {
charTotal++;
}
if (phrase[i] >= '0' && phrase[i] <= '9') {
numTotal++;
}
if ((phrase[i] >= 'A' && phrase[i] <= 'Z') || (phrase[i] >= 'a' && phrase[i] <= 'z')) {
letterTotal++;
}
if (phrase[i] == 'a' || phrase[i] == 'A' || phrase[i] == 'e' || phrase[i] == 'E' || phrase[i] == 'i' || phrase[i] == 'I' || phrase[i] == 'o' || phrase[i] == 'O' || phrase[i] == 'u' || phrase[i] == 'U') {
vowelTotal++;
}
consonTotal = letterTotal - vowelTotal;
if (phrase[i] == ' ') {
spacesTotal++;
}
specialCharTotal = (charTotal - (numTotal + letterTotal + spacesTotal));
}
cout << " Number of characters: " << charTotal << endl;
cout << " Number of numerics: " << numTotal << endl;
cout << " Number of alphabets: " << letterTotal << endl;
cout << "\tNumber of vowels: " << vowelTotal << endl;
cout << "\tNumber of consonants: " << consonTotal << endl;
cout << " Number of spaces: " << spacesTotal << endl;
cout << " Number of special characters: " << specialCharTotal << endl;
cout << " Your phrase in reverse: " << endl'
system("pause");
}
Make use of std::reverse:
std::string s = "reverse me";
std::reverse(s.begin(), s.end());
So im having a problem with rejecting decimals, Im rejecting any characters but when it comes to decimals it just seems not to be working. ((a % 1) != 0) was the equation i used
Also, I'm having a problem with the do loop, when the user inputs 'y' or 'Y' it seems to double the last value that was recorded from the previous test. I'm a freshman just trying to learn more so please help me out, guys.
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int whatItDoes(int* a, int* b)
{
int temp = *a;
*a = *b * 10;
*b = temp * 10;
return *a + *b;
}
int main()
{
int a;
int b;
bool input1 = false;
bool input2 = false;
double temp;
char again;
cout << "------------------" << endl;
cout << "solovesa WELCOME " << endl;
cout << "------------------" << endl;
do
{
while (!input1) //Validation
{
cout << "First integer: ";
string line;
cin >> line;
istringstream is(line);
char dummy = '\0'; //null termination char marks end of string
if (!(is >> a) || (is >> ws && is.get(dummy))) //ws meaning
{
cout << " " << endl;
cout << "WARNING: Characters are not allowed" << endl;
cout << " " << endl;
}
else
input1 = true;
if ((a % 1) != 0)
{
cout << " " << endl;
cout << "WARNING: Decimals are not allowed" << endl;
cout << " " << endl;
}
else
input1 = true;
}
while (!input2) //Validation
{
cout << "Second integer: ";
string line;
cin >> line;
istringstream is(line);
char dummy = '\0'; //null termination char marksd end of string
if (!(is >> b) || (is >> ws && is.get(dummy))) //ws meaning
{
cout << "Characters are not allowed" << endl;;
}
else
input2 = true;
}
cout << " " << endl;
whatItDoes(&a, &b);
cout << "Final: " << (a + b) << endl;
cout << " " << endl;
cin.clear();
//repeat program prompt
cout << "Would u like to do another set ? (Y/N)"; //ask user if they want to repeat
cin >> again;
//if they say no then exits program but if yes it repeats to top program
}
while (again == 'Y' || again == 'y');
system("pause");
return 0;
}
``````
Recommendation:
pass a and b by ref.
int whatItDoes(int* a, int* b) --> int whatItDoes(int& a, int& b)
Your Question:
if I understand your code correctly - an ascii character '.' translates to the numeric value of 46 (google Ascii table). So, 46 % 1 == 0.
You can explicitly check for the decimal, if( (a % 46) == 0 ), but be careful, as 0 % 46 == 0 (but character zero ('0') has a numeric value of 48 ).
Consider what I mentioned about the ASCII table and the numeric values of a char.
My code can compile but it doesn't return the character asked and it also does not follow the else statement since it will cout the error message after any input from the true if statement. Beginner in C++ so any help is appreciated.
// Python Challenge 2.cpp : This program will take a line of text from the user and then translate each letter 2 over in the alphabet.
//
#include "stdafx.h"
#include <iostream>
using namespace std;
char chChar;
char chChar2;
char chChar_a;
char chChar_b;
int main()
{
//This takes the one letter input from the user:
cout << "Type in a lowercase letter: ";
cin >> chChar;
//for letters a-x
if ((int)chChar >= 97 && (int)chChar <= 120)
char chChar2 = (int)chChar + 2;
cout << "is now: " << chChar2 << endl;
//for the letter y
if ((int)chChar == 121)
{
char chChar_a = '97';
cout << "is now: " << chChar_a << endl;
}
//for the letter z
if ((int)chChar == 122)
{
char chChar_b = '98';
cout << "is now: " << chChar_b << endl;
}
//for everything else
else
cout << "Error: type in a lowercase letter." << endl;
return 0;
}
Your if statement is not correct: you forgot to create a block using { } after it.
As it stands, the code does:
//for letters a-x
if ((int)chChar >= 97 && (int)chChar <= 120)
{
char chChar2 = (int)chChar + 2;
}
// Always runs the next part
cout << "is now: " << chChar2 << endl;
...
And the final else is attached to the if before it:
//for the letter z
if ((int)chChar == 122)
{
char chChar_b = '98';
cout << "is now: " << chChar_b << endl;
}
else
{
cout << "Error: type in a lowercase letter." << endl;
}
To fix this, add the proper brackets { }. An if without the brackets only conditionally executes the next statement, and not the block -- don't let indentations fool you: they have no meaning in C.
So, with this, your fixed code should look like:
//This takes the one letter input from the user:
cout << "Type in a lowercase letter: ";
cin >> chChar;
//for letters a-x
if ((int)chChar >= 97 && (int)chChar <= 120)
{
char chChar2 = (int)chChar + 2;
cout << "is now: " << chChar2 << endl;
//for the letter y
if ((int)chChar == 121)
{
char chChar_a = '97';
cout << "is now: " << chChar_a << endl;
}
//for the letter z
if ((int)chChar == 122)
{
char chChar_b = '98';
cout << "is now: " << chChar_b << endl;
}
}
//for everything else
else
{
cout << "Error: type in a lowercase letter." << endl;
}
return 0;
Starting from this, you can debug your code for further issues.
I'm writing a program in C++ that takes integers from the user until they press "x" to stop.
Then the program will print the number of positives, negatives and zeros.
But whenever the user inputs "x", the program goes into an infinite loop.
I tried removing the "ZEROS" part and just made counters for positives and negatives and it worked good. But I want to count the zeros.
I need to let the user enter numbers including 0 until they enter character x.
Here is my code:
#include <iostream>
using namespace std;
int main() {
int input, neg = 0, pos = 0, zer = 0;
char z;
do {
cout << "Input another positive/negative number or 'x' to stop\n";
cin >> input;
cin.ignore();
if (input > 0){
pos++;
} else if (input == 0){
zer++;
} else if(input < 0){
neg++;
}
} while (z!='x');
cout << "You entered " << pos << " positive numbers.\n";
cout << "You entered " << neg << " negative numbers.\n";
cout << "You entered " << zer << "Zeros.";
return 0;
}
By far the simplest way of getting numbers until a user enters something else is this:
int input = 0;
cout << "Input a positive/negative number or 'x' to stop\n";
while(cin >> input) {
//they entered a number, do stuff
if (input > 0)
pos++;
else if (input == 0)
zer++;
else if (input < 0)
neg++;
cout << "Input another positive/negative number or 'x' to stop\n";
}
//cin failed to read a number, probably because they entered a letter
//if they failed to enter a number, we need to clear the fail flag before we can use cin again
cin.setstate(cin.rdstate()&~std::ios_base::failbit);
cout << "You entered " << pos << " positive numbers.\n";
cout << "You entered " << neg << " negative numbers.\n";
cout << "You entered " << zer << "Zeros.";
I wouldn't recommend anything more complicated until you get very advanced with C++. Parsing input is immensely difficult to get correctly, and many experienced people get it wrong.
In order to correctly handle input errors and limit it so that only lower case x will break your loop, you need to do a lot of error checking:
#include <iostream>
#include <sstream>
#include <string>
int main()
{
int neg = 0;
int pos = 0;
int zer = 0;
std::string line;
while (std::cin >> line)
{
if (line == "x")
{
break;
}
std::istringstream iss(line); // convert to a stringstream
int val = 0;
if (!(iss >> val)) // if we can load an int, do it, otherwise show and error message
{
std::cout << "Please enter a valid number!" << std::endl;
continue;
}
if (val > 0)
{
pos++;
}
else if (val < 0)
{
neg++;
}
else
{
zer++;
}
}
std::cout << "You entered " << pos << " positive numbers.\n"
<< "You entered " << neg << " negative numbers.\n"
<< "You entered " << zer << " zeros." << std::endl;
return 0;
}
The problem is that an object of type int may not read symbols as for exmaple 'x' from a stream. It expects digits in an input stream. So when a symbol that can not be in a number is encountered in an input stream an error is arised. The stream will have erroneous state. If you will try again and again to read a number the stream will give nothing due to its state and the fact that the next symbol is for example non-digit.
So there is no sense to compare variable input with 'x'.
I would rewrite your loop the following way
while ( true )
{
int input;
cout << "Input another positive/negative number or 'x' to stop: ";
if ( !( cin >> input ) ) break;
if (input > 0)
{
pos++;
} else if (input == 0)
{
zer++;
} else
{
neg++;
}
}
check this out
#include <iostream>
#include<string>
using std::string;
using std::getline;
using namespace std;
int main()
{
string input;
int neg = 0, pos = 0, zer = 0;
char z;
input = "";
int iVal = 0;
do
{
cout << "Input another positive/negative number or 'x' to stop\n";
getline(cin, input);
iVal = atoi(input.c_str());
if (input != "x" && input !="X")
{
if (iVal > 0)
{
pos++;
} else if (iVal == 0)
{
zer++;
} else if(iVal < 0)
{
neg++;
}
}
} while (input != "x" && input != "X");
cout << "You entered " << pos << " positive numbers.\n";
cout << "You entered " << neg << " negative numbers.\n";
cout << "You entered " << zer << " zeros.\n";
return 0;
system("pause");
}
IT goes into the loop for a few reasons
1)You declared input as an integer, for this purpose ypu would have to declare it as char data type in order to do your validation on it
2)You dont have a if condition for x eg else if (input =='x')
I got this program to calculate the grades to its corresponding letter grade, and I got it to loop as many times as the user wants to output. However, for some reason it only writes the last known output to its text file. Can anyone tell me what I am doing wrong here?
#include <fstream>
#include <iostream>
#include <iomanip>
#include <string>
#include <cstdlib>
int weighted1 = 0;
int weighted2 = 0;
int weighted3 = 0;
int weighted4 = 0;
int weighted_average = 0;
const int MAX = 20;
int flag = 0;
int choice;
double sum = 0;
double average = 0;
char name [10];
char letter;
char file [MAX];
int num = 0;
int count = 0;
int main( )
{
//Initiate input/output stream
std::ifstream in_stream;
std::ofstream out_stream;
in_stream.open("grade.txt");
out_stream.open("finalgrade.dat");
double first, second, third, fourth;
in_stream >> first >> second >> third >> fourth >> name;
//std::cout >> " 1: " >> first >> " 2: " >> second >>
double grade = 0.0;
grade = (first + second + third + fourth)/4;
//Gives user the choice of reading student records from keyboard or file
bool menu = true;
while (menu != false)
{
std::cout << "Would you like to open as keyboard or file?" << '\n';
std::cout << "1. keyboard" << '\n';
std::cout << "2. file" << '\n';
std::cin >> choice;
switch (choice)
{
//Enter the number students the grades will enter
case 1:
std::cout << "How many students? ";
std::cin >> num;
for(count =0; count < num; count++)
{
{
std::cout << "Student's Name: ";
std::cin >> name;
}
do
{
flag = 0;
std::cout << "Please input your first exam grade and press enter: \n";
std::cin >> first;
if ((first < 0) || (first > 100))
{
std::cout << "You've entered invalid data!" << '\n';
flag = 1;
}
}while (flag == 1);
do
{
flag = 0;
std::cout << "Please input your second exam grade and press enter: \n";
std::cin >> second;
if ((second < 0) || (second > 100))
{
std::cout << "You've entered invalid data!" << '\n';
flag = 1;
}
}while (flag == 1);
do
{
flag = 0;
std::cout << "Please input your third exam grade and press enter: \n";
std::cin >> third;
if ((third < 0) || (third > 100))
{
std::cout << "You've entered invalid data!" << '\n';
flag = 1;
}
}while (flag == 1);
do
{
flag = 0;
std::cout << "Please input your final exam grade and press enter: \n";
std::cin >> fourth;
if ((fourth < 0) || (fourth > 100))
{
std::cout << "You've entered invalid data!" << '\n';
flag = 1;
}
}while (flag == 1);
//Formulas that calculate student average
grade = (first + second + third + fourth)/4;
sum = first + second + third + fourth;
average = sum/4;
//Letter grade and it's weighted averages
letter = 'A';
letter = 'B';
letter = 'C';
letter = 'D';
letter = 'F';
if(grade >= 90)
{
letter = ('A');
std::cout<<letter<<'\n';
}
else if(grade >= 80)
{
letter = ('B');
std::cout<<letter<<'\n';
}
else if(grade >= 70)
{
letter = ('C');
std::cout<<letter<<'\n';
}
else if(grade >= 60)
{
letter = ('D');
std::cout<<letter<<'\n';
}
else if (grade < 60)
{
letter = ('F');
std::cout<<letter<<'\n';
}
weighted1 = (first * .20);
weighted2 = (second * .20);
weighted3 = (third * .20);
weighted4 = (fourth * .40);
weighted_average = (weighted1 + weighted2 + weighted3 + weighted4);
//Output
std::cout << "Exam Grades: " << first << "," << second << "," << third << "," << fourth << '\n';
std::cout << "This is the average for " << name << ": " << weighted_average << '\n';
std::cout << "This is the letter grade: " << letter << '\n';
}
{
//Writing the grade into grades.txt
for(count =0; count < num; count++)
{
std::ofstream myfile;
myfile.open ("grades.txt");
myfile << "Writing this to a file: ";
myfile << name << ' ';
myfile << weighted_average << ' ';
myfile << letter << '\n';
myfile << "****";
myfile.close();
}
break;
}
//Here we open "grade.txt" to output grade to screen
case 2:
in_stream.open("grade.txt");
out_stream.open("finalgrade.dat");
letter = 'A';
letter = 'B';
letter = 'C';
letter = 'D';
letter = 'F';
if(grade >= 90)
letter = ('A');
else if(grade >= 80)
letter = ('B');
else if(grade >= 70)
letter = ('C');
else if(grade >= 60)
letter = ('D');
else if (grade < 60)
letter = ('F');
weighted1 = (first * .20);
weighted2 = (second * .20);
weighted3 = (third * .20);
weighted4 = (fourth * .40);
weighted_average = (weighted1 + weighted2 + weighted3 + weighted4);
std::cout << "Enter file name: ";
std::cin >> file;
if(file != "grade.txt")
{
std::cout << std::fixed << "The average grade for: " << name << '\n';
std::cout << "average in grade.txt is: "<< weighted_average << std::setprecision(2) << '\n';
std::cout << "and the letter grade is: " << letter << '\n';
}
else
{
return 0;
}
in_stream.close();
out_stream.close();
}
return 0;
}
}
EDIT: The more serious issue here is that you're only storing the last input. You should create an object to store all of the data for each student (e.g. a Student object), create an array of students, and loop through that array to print the information after you have all of your input. I've updated the code below to what it would look like for an array of objects.
If you don't know any object-oriented programming concepts, you could also put each piece of data (name, letter grade, average, etc.) in an array, where the 0th element in each would all represent one student, the 1st would represent another, etc. This isn't good practice; it's a much better idea to create an object to store the information about a student.
Original: You're overwriting your file instead of appending to it by opening and closing it inside every iteration of the loop.
Instead, open your file before the loop and close it after, like this:
{
//Writing the grade into grades.txt
std::ofstream myfile;
myfile.open ("grades.txt");
for(count =0; count < num; count++)
{
myfile << "Writing this to a file: ";
myfile << students[count].name << ' ';
myfile << students[count].weighted_average << ' ';
myfile << students[count].letter << '\n';
myfile << "****";
}
myfile.close();
}
if your trying to output many things i suggest you
Iterate through the loop adding your intended output to a variable, after the loop finishes output that variable
Example
var output
while(true) {
add to output
}
print output