How to cause a C++ program to exit - c++

I'm trying to make my C++ program exit.
I know I can pause input with while cin >> s, but I don't know what to do to make the entire program exit.
This is my code:
int main()
{
long int l;
long int i;
char s[100000];
while (cin >> s)
{
l = strlen(s);//strlen Returns the length of the C string str.
for (i = 0; i<l; i++)
{
switch (s[i])
{
case 'W':
cout << "Q"; break;
case 'E':
cout << "W"; break;
case 'R':
cout << "E"; break;
default:
cout << ";"; break;
}
}
cout << (" ");
}
system("pause");
return 0;
}

Your program will terminate when it runs out of input.
The system("pause"); seems to imply that you're using Microsoft Windows. To signal an end-of-file condition for keyboard input on Windows, type Ctrl-Z. (For Linux and other Unix-like systems, use Ctrl-D at the beginning of a line.)
Incidentally, the program you posted is complete and will not compile. That can be corrected by adding the following lines to the top:
#include <iostream>
#include <cstdlib>
#include <cstring>
using namespace std;
When posting a question, please include the entire program.

I was able to get the program to exit by using the command exit(0); within the while loop.
Here is my finished program:
include iostream
include string
using namespace std;
int main(){
long int l;
long int i;
char s[100000];
cout << "\n Write your code in UpperCase, "
cout << "to close the program switch to LowerCase \n" << endl;
while (cin >> s)
{
l = strlen(s);//strlen Returns the length of the C string str.
for (i = 0; i<l; i++)
{
switch (s[i])
{
case 'W':
cout << "Q"; break;
case 'E':
cout << "W"; break;
case 'R':
cout << "E"; break;
default:
exit(0); break;
}
}
cout << (" ");
}
system("pause");
return 0;
}

Your loop is waiting until cin >> s returns an "end of file" (EOF). You can accomplish this on Windows by typing Ctrl+Z or on Unix-like systems such as Mac and Linux Ctrl+D.
You could also put a break character in your loop, or change the condition altogether.

Related

cout is only working after gets() eventhough i had written it before gets()

I have just started learning c++.
I wrote this program for finding how many vowels in a sentence.
But when i run the program it asking for input before the cout and cout is working after gets()
#include <iostream>
#include <cstdio>
using namespace std;
int main() {
char str[50];
int vow;
cout<<"Type a sentence";
gets(str);
for(int i=0; str[i]!='\0';i++){
switch(str[i]){
case 'a':
case 'e':
case 'i':
case 'o':
case 'u': vow++;
}
}
cout<<"There are "<<vow<<" vowels in the string "<<str;
return 0;
}
output
hello world
Type a sentenceThere are 3 vowels in the string hello world
The problem is that std::cout is buffered, and you are not flushing the buffer to the console before calling gets(), which has no concept of std::cout or its buffer. So, you will have to flush the buffer manually, either by writing a '\n' character to the output, eg:
cout << "Type a sentence\n";
gets(str);
Or, using the std::endl or std::flush manipulator:
cout << "Type a sentence" << endl; // writes '\n' and then flushes
gets(str);
cout << "Type a sentence" << flush; // just flushes without writing '\n' first
gets(str);
Or, calling the std::cout.flush() method directly, eg:
cout << "Type a sentence";
cout.flush();
gets(str);
But, you really should not be mixing C-style I/O and C++-stye I/O. std::cin and std::cout are tie()'d together by default, so if you had used std::cin instead of gets() to read the input, then std::cin would have first flushed std::cout's buffer automatically.
Try this instead:
#include <iostream>
using namespace std;
int main() {
char str[50] = {};
int vow = 0;
cout << "Type a sentence: ";
cin.getline(str, 50);
for(int i = 0; str[i] != '\0'; ++i){
switch (str[i]){
case 'a':
case 'e':
case 'i':
case 'o':
case 'u': vow++;
}
}
cout << "There are " << vow << " vowels in the string " << str;
return 0;
}
Or, using std::string instead of char[]:
#include <iostream>
#include <string>
using namespace std;
int main() {
string str;
int vow = 0;
cout << "Type a sentence: ";
getline(cin, str);
for(size_t i = 0; i < str.size(); ++i){
switch (str[i]){
case 'a':
case 'e':
case 'i':
case 'o':
case 'u': vow++;
}
}
cout << "There are " << vow << " vowels in the string " << str;
return 0;
}

How to ignore all characters except first character?

#include <iostream>
using namespace std;
int main ()
{
char letter;
while (cin>>letter)
{
switch (letter)
{
case 'a':
cout<<"ant"<<endl;
break;
default :
cout <<"enter only lower cases letters "<<endl;
}
}
return 0;
}
Is there any feature of c++ that ignores the characters next to first character? Because i.e., if I enter aaa it displays ant ant ant, so I want to get rid of this part. I hope you get my question.
Read a string and then switch on the first character. Like this.
int main () {
string word;
while (cin >> word) {
switch (word[0]) {
case 'a':
cout << "ant" << endl;
break;
default:
cout << "enter only lower cases letters " << endl;
break;
}
}
return 0;
}
You can treat the user input as a std::string and then just look at the first character from it for your switch statement. This will ignore anything the user inputs after the first character. I can't imagine the use case for this, but I believe this is what you're asking for.
#include <cstdlib>
#include <iostream>
int main( int argc, char *argv[] )
{
std::string word;
while (std::cin >> word)
{
char letter = word[0];
switch (letter)
{
case 'a':
std::cout << "ant" << std::endl;
break;
default:
std::cout << "please enter only lower case letters" << std::endl;
break;
}
}
return EXIT_SUCCESS;
}
Read chars repeatedly and keep track of what's been added
#include <set>
int main () {
char letter;
std::set<char> used;
while (cin >> letter) {
if (!used.insert(letter)[1]) // note returns a pair; 2nd item ([1]) is true if it didn't exist before
continue;
switch (letter) {
case 'a':
cout << "ant" << endl;
break;
default:
cout << "enter only lower cases letters " << endl;
break;
}
}
return 0;
}
Only first char will be saved
int main()
{
char c = 0;
c = getchar();
putchar(c);
return 0;
}

Counting vowels and consonants [closed]

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
My program keeps crashing every time I enter an input even though I use a system pause method and displays the same number of vowels and consonants that is incorrect. What's going on?
int main() {
// declare vars
char ch;
int vowels = 0;
int consonants = 0;
string word = "temp";
// prompt user
cout << "Please enter a word: ";
cin >> ch;
// loop vowels and consonants
for (int i = 0; i < word.size(); i++) {
ch = toupper(word[i]);
switch (ch) {
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
vowels++;
break;
default:
consonants++;
}
}
// show num of vowels and consanants
cout << "Number of Vowels: " << vowels << endl;
cout << "Number of Consanants: " << consonants << endl;
// pause and exit
getchar();
getchar();
return 0;
}
Normally it's better to input a full string and then parse... but if for some reason you need to stream characters as they are entered you can use cin.get(). make sure to #include <cctype> if you want to use toupper().
char nextChar;
nextChar = cin.get();
nextChar = toupper(nextChar);
int consonants = 0;
int vowels = 0;
int words = 0;
while (nextChar != '\n')
{
switch (nextChar)
{
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
vowels++:
break;
case ' ':
words++;
break;
default:
consonants++;
break;
}
}
cout << "There were " << consonants << " consonants and " << vowels << " vowels in " << words << " words.";
instead of ending on a newline, if you want to limit to one word simply replace (nextChar != '\n') with (nextChar != ' ').
The only change that needs to occur is the change from:
cin >> ch;
to
cin >> word;
And you code will be fine. Live example
Some chages in your code :
#include <iostream>
#include <string>
using namespace std;
int main() {
// declare vars
char ch;
int vowels = 0;
int consonants = 0;
string word = "temp";
// prompt user
cout << "Please enter a word: ";
cin >> word;
// loop vowels and consonants
for (int i = 0; i < word.size(); i++) {
ch = toupper(word[i]);
switch (ch) {
case 'A':
vowels++;
break;
case 'E':
vowels++;
break;
case 'I':
vowels++;
break;
case 'O':
vowels++;
break;
case 'U':
vowels++;
break;
default:
consonants++;
}
}
// show num of vowels and consanants
cout << "Number of Vowels: " << vowels << endl;
cout << "Number of Consanants: " << consonants << endl;
// pause and exit
getchar();
getchar();
return 0;
}
Okay, so this isn't quite an answer, but it's a bit too detailed to put into a comment...
I just ran your code and it worked fine. I added the following three libraries
#include<string>
#include<iostream>
#include<stdio.h>
And then:
using namespace std;
and then compiled with g++ filename.
Check to make sure you're libraries are up to date and that you're compiling the code correctly.
Hope this helps.

How to make an exit in switch case implementation with user prompt?

I've a basic computing program, in it I want that when a user wants to just quit the program in his very first input without making any calculation, the program just exits. But rather here if the user enters q for quit/exit in his first input the programs runs into an infinite loop. Is there any way to provide user with some single exit key which when entered anytime(by the user) during runtime just quits the program. The innermost while loop works fine unless the outermost loop stops working.
#include "std_lib_facilities.h"
int main() {
double x = 0, y = 0, result = 0;
string operation = " ";
char op = ' ';
cout << "\nInput (e.g. -> 5*6)\nPress q to quit.\n";
while(1) {
cin >> x >> op >> y;
switch(op) {
case '+':
result = x + y;
operation = "sum";
break;
//Other switch cases
case 'q':
exit(1);
default:
cout << "Invalid input.";
break;
}
cout << "The " << operation << " of " << x << " and " << y << " is "
<< result << ".\n\n"
<< "If you have another input, press any character to continue..\n"
<< "Else press q to quit.\n";
// exit or continue program loop
while(cin >> op) {
if(op=='q' || op=='Q')
exit(1);
else
cout << "Provide next set of inputs.\n";
break;
}
}
}
If the user enter q on the first try then the stream will try to read this value to x which is a double which will fail and the state of the stream will be set to fail, after that no other I/O operation will be successfully performed and the loop will run infinitely.
You could probably check for the state of the stream just before you ask the user to continue or quit and clear the stream state if the previous operation was failed:
if(cin.fail())//check if the previous read operation failed
cin.clear();//clear the stream state,so the next cin will read what is in the buffer
while(cin >> op)
...//your other code
Try this:
boolean quit = FALSE;
while (!quit)
{
...
switch (op)
{
case 'q':
quit = TRUE;
break;
}
}
#include<iostream>
#include<stdlib.h>
using namespace std;
int main()
{
char ch;
while(true)
{
cout<<"l.print l "<<endl<<"c.print c "<<endl<<"q. exit"<<endl;
cout<<"enter choice"<<endl;
cin>>ch;
switch(ch)
{
case 'l':
cout<<"You have typed l "<<endl;
break;
case 'c':
cout<<"You have typed c"<<endl;
break;
case 'q':
cout<<"Exit ..." <<endl;
exit(0);
default:
cout<<"Wrong choice "<<endl;
}
}
return 0;
}

I think there's a slight mistake that my C++ textbook is giving me about switch statement

#include <iostream>
using namespace std;
int main()
{
int grade;
int aCount;
int bCount;
int cCount;
int dCount;
int fCount;
cout << "Enter the letter grades." << endl
<< "Enter the EOF character to end input." << endl;
while ((grade = cin.get()) != EOF)
{
switch (grade)
{
case 'A':
case 'a':
aCount++;
break;
case 'B':
case 'b':
bCount++;
break;
case 'C':
case 'c':
cCount++;
break;
case 'D':
case 'd':
dCount++;
break;
case 'F':
case 'f':
fCount++;
break;
case '\n':
case '\t':
case ' ':
break;
default:
cout << "Incorrect letter grade entered." << "Enter a new grade." << endl;
break;
}
}
cout << "\n\nNumber of students who received each letter grade:"
<< "\nA: " << aCount
<< "\nB: " << bCount
<< "\nC: " << cCount << "\nD: " << dCount << "\nF: " << fCount << endl;
system("PAUSE");
return 0;
}
This is an exact code provided by my C++ textbook. While I was practicing these switch statement codes by copying these codes then compile it, my Visual Studio 2010 express keep gives me an error saying that "aCount is being used without assigned..." same applies to fCount. This program should read any letter from A to F from a keyboard then increment whatever letter that was recognized. I think there should be cin>>grade somewhere in the codes but I don't find it. By the way, can "cin.get()" could work as cin>>grade??
When you are declaring your variables try giving them the value of 0 like this:
int grade = 0;
int aCount = 0;
int bCount = 0;
int cCount = 0;
int dCount = 0;
int fCount = 0;
This will ensure that you are in fact assigning a value to the variable before it is being used.
Then try to run it, I bet it works!
It is advisable for you to initialize your variables being using it. Some compiler will not even give you a warning before compilation, but assigns some "garbage values" to your un-initialize variables.
Initializing your variables to 0 is suffice in this scenario (Like what other user mentioned).
int grade=0;
int aCount=0;
int bCount=0;
int cCount=0;
int dCount=0;
int fCount=0;
By the way, can "cin.get()" could work as cin>>grade??
That depends on how you want to use it. cin.get can be used to extract a:
single character
multiple characters and store them as c-string (char array) or
store them into a stream buffer object
from the input stream.
You may realize cin.get can't accept numbers, so if you are accepting input of characters or string, it is fine. But in future, if you want it to accept numbers, just use cin >> number
An example on using cin.get()
char cStr[50];
cin.get(cStr,5); //It will take n-1 characters
cout << cStr;
//Input: abcde
//Output: abcd