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');
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
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;
}
#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;
}
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;