How to stop a while loop in c++ - c++

"Write a program that consists of a while-loop that (each time around the loop) reads in two ints and then prints them.
Exit the program when a terminating '|' is entered."
my attempt
#include <iostream>
#include <cstdlib>
using namespace std;
int main(){
int firstnumber;
int secondnumber;
int stopnumber;
while(stopnumber!='|'){
cout <<"Please enter an integer, followed by another integer: \n";
cin >> firstnumber >> secondnumber;
cout <<"\n" << firstnumber <<" "<< secondnumber<< " \n";
}
return 0;
}
the program takes 2 number and prints them, but when i enter '|' , it goes in infinite loop. How to stop the program when i enter '|'
Thanks

This is how your loop should look like:
Read a character (std::cin::get).
If successful and your character is the stop symbol, break the loop.
If your character is not a digit (::isdigit), continue looping.
If your character is a digit, put it back(std::cin::putback).
Read two integers.
If successful, display them, if not, clear the stream (std::cin::clear).
You will have to patiently try to understand what get, putback & isdigit are doing.
[EDIT]
Run it
#include <iostream>
#include <cctype>
int main()
{
char c;
while ( std::cin.get( c ) && c != '|' )
{
if ( !std::isdigit( c ) )
continue;
std::cin.putback( c );
int i, j;
if ( std::cin >> i >> j )
std::cout << i << ' ' << j << std::endl;
else
std::cin.clear();
}
return 0;
}

Your loop is testing stopnumber which is never set. If you set stopnumber to either firstnumber or secondnumber then perhaps you can get your logic to work but there is a step missing as it is.

Ok, I think I have found my answer
I tried putting my cin in the while loop as such
int firstnumber;
int secondnumber;
while (cin >> firstnumber >> secondnumber)
And it worked! Thanks everyone for your help

This depends on whether you need to exit directly after you receive the '|' character or whether you mind running through the rest of the loop first before exiting it......
Personally I'd want to exit straight after receiving the '|' so would follow the basic idea of....
int a,b;
while(){
read your values a,b in
if (a='|' || b='|'){exit()};
print your values
}

std::stoi(std::string) - returns int from std::string
#include <iostream>
#include <string>
bool isNumber(std::string &str) {
for (auto i : str) {
if (i < '0' || i > '9') return false;
return true;
}
int main () {
int a, b;
std::string s;
while (true) {
std::cin >> s;
if (s == "|" || !isNumber(s)) break;
a = std::stoi(s);
std::cin >> s;
if (s == "|" || !isNumber(s)) break;
b = std::stoi(s);
std::cout << a << " " << b << std::endl;
}
return 0;
}

Related

Ending an input stream with a specified character, such as '|'?

Currently learning C++, newbie.
I have an issue when ending the input with the '|' character, my program skips to the end/ends and does not allow for further input. I believe it is because std::cin is in an error state due to inputting a char when expecting an int, so i have tried to use std::cin.clear() and std::cin.ignore() to clear the issue and allow the remainder of the programme to run but I still cannot seem to crack it, any advice appreciated.
int main()
{
std::vector<int> numbers{};
int input{};
char endWith{ '|' };
std::cout << "please enter some integers and press " << endWith << " to stop!\n";
while (std::cin >> input)
{
if (std::cin >> input)
{
numbers.push_back(input);
}
else
{
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max());
}
}
And then pass the vector to a function to iterate through x amount of times and add each element to a total, but the program always skips past the user input:
std::cout << "Enter the amount of integers you want to sum!\n";
int x{};
int total{};
std::cin >> x;
for (int i{ 0 }; i < x; ++i)
{
total += print[i];
}
std::cout << "The total of the first " << x << " numbers is " << total;
Please help!
When the use enters a "|" (or anything that is not an int), the loop ends and the error handling that is inside the loop does not execute. Just move the error code to outside the loop. Also, you read from stdin twice which will skip every other int.
while (std::cin >> input) {
numbers.push_back(input);
}
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
Note: If you want to specifically check for "|" can change to something like this:
while (true) {
if (std::cin >> input) {
numbers.push_back(input);
}
else {
// Clear error state
std::cin.clear();
char c;
// Read single char
std::cin >> c;
if (c == '|') break;
// else what to do if it is not an int or "|"??
}
}
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

Recursive version of strlen in c Strings c++

I am struggling with an assignment for my first c++ class. I am hoping someone can help me in the right direction. I need to write a "recursive version of strlen in c strings." According to my handout, my function should look like this, "int str_length(char s[])".
My main problem is trying to get the user to enter a string or cstring of an undetermined length and use it for the function call. I would really appreciate all the help and direction I can get.
I have played around with my code so much now that I am rather lost. It would seem I would fix one issue and create a new one. I think I have my function written correctly but here is the code if there is a better/correct way of doing it.
#include <iostream>
#include <cstring> //included both until I find my solution
#include <string>
using namespace std;
//string or char sentence; This part of my struggle
char choice = 'Y';
int str_length(char s[]);
int main()
{
while ((choice != 'n') && (choice != 'N'))
{
cout << "Enter a sentence. ";
//user entry cin, getline etc
cout << sentence;
//cout << str_length(sentence);
cout << endl;
cout << "Do you want to have another run? Y/N ";
cin >> choice;
}
}
int str_length(char s[])
{
// if we reach at the end of the string
if (s == '\0')
{
return 0;
}
else
{
return 1 + str_length(s + 1);
}
}
There is already the standard C function strlen that has the following declaration
size_t strlen( const char *s );
So your recursive function should have the same declaration. It can be implemented the following way
size_t strlen( const char *s )
{
return *s == '\0' ? 0 : 1 + strlen( s + 1 );
}
A program that tests the function can look like
#include <iostream>
#include <string>
#include <limits>
size_t strlen( const char *s )
{
return *s == '\0' ? 0 : 1 + strlen( s + 1 );
}
int main()
{
char choice;
do
{
std::cout << "Enter a sentence: ";
std::string sentence;
std::getline( std::cin, sentence );
std::cout << "The length of the sentence is "
<< strlen( sentence.c_str() )
<< '\n';
std::cout << "Do you want to have another run (Y/N)? ";
std::cin >> choice;
std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
} while ( choice == 'y' || choice == 'Y' );
}
Its output might be
Enter a sentence: Hello user12446497
The length of the sentence is 18
Do you want to have another run (Y/N)? n

I want to take a number from the user and if he type a character or anything else i want him to enter the number again

int x;
if(cin >> x)
cout << "True" << endl;
else
{
cin >> x;
}
It supposes to let me enter the number again but it's end the program without taking the number again
A simple solution is to get the input as string, use regex to check if it's a number and if it is convert it to an int, otherwise ask for input again. Here's an example:
#include <iostream>
#include <string>
#include <regex>
int main() {
std::regex rx(R"((?:^|\s)([+-]?[[:digit:]]+(?:\.[[:digit:]]+)?)(?=$|\s))");
std::string line;
int n;
while ( std::getline(std::cin, line) ) {
if ( std::regex_match(line, rx) ) {
// Input is number
n = std::stoi( line );
std::cout << n << "\n";
break;
}
}
return 0;
}

How to check if the input is a valid integer without any other chars?

#include <iostream>
#include <limits>
using namespace std;
int main()
{
int x;
cout << "5 + 4 = ";
while(!(cin >> x)){
cout << "Error, please try again." << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
if (x == (5 + 4)){
cout << "Correct!" << endl;
}
else{
cout << "Wrong!" << endl;
}
return 0;
}
How can I check if the user inputs a valid integer? In this program I wrote above, if the user inputs 9, it should be correct, however, if the user inputs 9a for example, it should return an error, but it doesn't for some reason. How can I correct it?
How I did it using cin.peek()
#include <iostream>
#include <limits>
#include <stdio.h>
using namespace std;
int main()
{
int x;
bool ok;
cout << "5 + 4 = ";
cin >> x;
while(!ok){
cin >> x;
if(!cin.fail() && (cin.peek() == EOF || cin.peek() == '\n')){
ok = true;
}
else{
cout << "Error, please try again." << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
}
if (x == (5 + 4)){
cout << "Correct!" << endl;
}
else{
cout << "Wrong!" << endl;
}
return 0;
}
You could read a string, extract an integer from it and then make sure there's nothing left:
std::string line;
std::cin >> line;
std::istringstream s(line);
int x;
if (!(s >> x)) {
// Error, not a number
}
char c;
if (s >> c) {
// Error, there was something past the number
}
bool isIntegerNumber(const std::string& string){
std::string::const_iterator it = string.begin();
int minSize = 0;
if(string.size()>0 && (string[0] == '-' || string[0] == '+')){
it++;
minSize++;
}
while (it != string.end() && std::isdigit(*it)) ++it;
return string.size()>minSize && it == string.end();
}
You have a line oriented input, so you should probably be using
getline. Something like:
bool
getIntFromLine( std::istream& source, int& results )
{
std::string line;
std::getline( source, line );
std::istringstream parse( source ? line : "" );
return parse >> results >> std::ws && parse.get() == EOF;
}
should do the trick.
Using this, your loop would be:
while ( !getIntFromLine( std::istream, x ) ) {
std::cout << "Error, please try again." << std::endl;
}
Note that this technique also means that you don't have to worry
about clearing the error or resynchronizing the input.
For the reason this happens, take a look at this link:
Extracts and parses characters sequentially from the stream to
interpret them as the representation of a value of the proper type,
which is stored as the value of val. Internally, the function accesses
the input sequence by first constructing a sentry object (with
noskipws set to false). Then (if good), it calls num_get::get (using
the stream's selected locale) to perform both the extraction and the
parsing operations, adjusting the stream's internal state flags
accordingly. Finally, it destroys the sentry object before returning.
Then observe the behavior if you attempt something like this:
int x = 0;
cin >> x;
std::cout << x << std::endl;
std::cout << cin.good() << std::endl;
g++-4.8 -std=c++11 -O3 -Wall -pedantic -pthread main.cpp && echo "900a100" | ./a.out
// Output:
// 900
// 1
If you input "a100" instead, it outputs:
0
0
try this:
std::string input;
std::cin >> input;
if ( std::all_of(input.begin(), input.end(), std::isdigit) )
{
//input is integer
}
Refer this :
C++ Fix for checking if input is an integer
One I have seen that works for some situations is:
Read the input as string. cin >> str
Decode to number: atoi, or sscanf, or stringstream, etc.
print the number into a string (using sprintf or stringstream)
check if its equal to read string. (using strings ==, not char*)
Quick and simple to do. Uses the Cin>>str word breaking rules, accept negative numbers, rejects overflowing numbers. But it does reject "+10", which in somesituations you are happy wiht, and in some you are not.
If you can use C++11 (and your compiler has full regex support), you can also use the <regex> library:
#include <iostream>
#include <limits>
#include <regex>
#include <string>
#include <utility>
int main()
{
std::string line;
std::pair<int, bool> value = std::make_pair(0, false);
std::cout << "5 + 4 = ";
while (!value.second)
{
while (!std::getline(std::cin, line))
{
std::cout << "Error, please try again." << std::endl;
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
if (!std::regex_match(line, std::regex("(\\+|-)?[[:digit:]]+")))
{
std::cout << "Error, please try again." << std::endl;
}
else
{
value = std::make_pair(std::stol(line), true);
}
}
if (value.first == (5 + 4))
{
std::cout << "Correct!" << std::endl;
}
else
{
std::cout << "Incorrect!" << std::endl;
}
return 0;
}

C++ How can I search a text file for the number of occurrences of a specific integer?

I am trying to write a program which will ask the user to input an integer, and will then proceed to search a predefined text file (containing integers only) for the number of occurrences of that specific integer, printing the result. Here is what I have coded so far (doesn't work when I run it), but I don't know if I'm going in the right direction here, or if I should be trying to read all the integers from the file into an array, or even do something else entirely. I should add that this is for homework, and I am just looking for pointers, not a full solution. I have tried everything I can think of, and haven't been making much progress. Could someone point me in the right direction? Thanks in advance.
#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;
int main()
{
int x, y;
int sum1 = 0;
ifstream infile ("file.txt");
if (infile)
cout << "File successfully opened" << endl;
else
{
cout << "Can't open file" << endl;
exit (EXIT_FAILURE);
}
cout << "Input number: ";
cin >> x;
int number;
while(!infile.eof()) //this is where my problems start
{
infile >> number;
}
while(number = x) //doesn't seem to be working, not sure if I should even be using
//a while statement
{
sum1++;
}
cout << sum1++ << " " ;
}
You are using single = in comparison statement: while(number = x) which is wrong. use == in comparison
Do it like:
while(number == x) //note ==
^^
Other thing to note is that you are using while 2 times that's logically not good and using !infile.eof() is also not good as you may not get expected results (1 more than original)
Try this code:
int number;
while (true) {
infile >> number;
if( infile.eof() ) //This line will help in avoiding processing last value twice
break;
if (number == x)
{
sum1++;
cout << sum1++ << " " ;
}
}
Do this:
// ...
int number;
infile >> number;
while(!infile.eof())
{
if (number == x)
{
sum1++;
}
infile >> number;
}
cout << sum1;