Ignoring a line beginning with a '#' in command prompt - c++

I am writing a code which requires me to ignore comment lines (i.e, lines beginning with a # sign) till the end of the line. I'm using linux to code in c++. For e.g: in case of adding two numbers.
xxx#ubuntu:~ $ ./add
Enter the two numbers to be added
1 #this is the first number
2 #this is the second number
result: 3
So the comment line can be anywhere. It just has to ignore the entire line and take the next value as input.
#include <iostream>
using namespace std;
int main()
{
int a,b;
cout<< "Enter the two numbers to be added:\n";
while(cin >>a >>b)
{
if (a == '#'|| b == '#')
continue;
cout << "Result: "<<a+b;
}
return 0;
}

From what you have shown, I think this might be what you want.
int main()
{
string comment;
int nr1,nr2;
// Read the first number. It should be the first one always. No comment before number!
cin >> nr1;
// See if we can read the second number Successfully. Which means it is an integer.
if(cin >> nr2) {
}
// Otherwise clear cin and read the rest of the comment line
else {
cin.clear();
getline(cin,comment);
// Now read the second number from the second line
cin >> nr2;
}
// Read the rest of second the line.
getline(cin,comment);
cout << "result: " << nr1 + nr2 << endl;
return 0;
}

Will any number of numbers based on the value you give reqd.
Will also work if the first character in a line itself is # - will ask again for that line. Will also read another line if there is no number before the `#.
#include <iostream>
#include <sstream>
#include <ctype.h>
using namespace std;
int main ()
{
const int reqd = 2;
string sno[reqd];
int no[reqd];
int got = 0;
size_t pos;
istringstream is;
cout<< "Enter "<<reqd<<" numbers to be added:\n";
while(got < reqd)
{
getline(cin, sno[got]);
if((pos = sno[got].find('#')) && isdigit(sno[got][0]))
{
is.str(sno[got]);
is>>no[got];
++got;
}
}
int sum = 0;
for(int i = 0; i < reqd; ++i)
sum+=no[i];
cout<<"Result : "<<sum;
return 0;
}

Related

My question = until user press "enter" take average from user inputs in c++

This code calculates the average from user that user inputs integer until user inputs "666" integer. However, I want to make it stop when the user just presses the enter key. How can I achieve this?
#include <iostream>
using namespace std; //s
int main()
{
int total = 0, counter = 0, number, average;
do
{
cin >> number;
if(number == 666) //what should i do to make enter button instead of 666?
{
average = total / counter;
cout << average;
return 0;
}
total = total + number;
counter = counter + 1;
} while(1);
return 0;
}
Sadly, you cannot check that easily if the <ENTER> button has been pressed. cin reads formatted input (numbers in your case) and ignores everything else (including whitespaces, like newline). A solution to your problem is to read a whole line and extract the numbers from it:
#include <iostream> // cin, cout
#include <sstream> // istringstream
#include <string> // getline
int main()
{
// Reading a line from the standard input to the variable 'line'.
std::string line;
std::getline(std::cin, line);
// The easiest way to get the numbers from 'line' is to wrap it in an
// 'istringstream'. Now, you can use 'iss' just like 'cin'.
std::istringstream iss{line};
double total = 0.0;
double counter = 0.0;
for (double number; iss >> number; ++counter) {
total += number;
}
std::cout << "Avarage: " << total / counter << '\n';
return 0;
}
I have been found the solution:
note that I use Code::Blocks compiler and I had to make a adjustment.
Settings> compiler > tick on the """have g++ follow the c++11 ISO C++ language standard [-std=c++11]""" box and click OK.
solution is below:
#include <iostream>
#include <string>
using namespace std;
int main() {
float c = 0, sum = 0;
string input;
while (true) {
cout << "input number:";
getline(cin,input);
if (input == "") {
cout << "average:" << sum / c << endl;
break;
}
sum += stof(input);
c++;
}
return 0;
}

How to simulate user input to std::cin for a mcve? [duplicate]

If we have this code snippet:
int a;
cout << "please enter a value: ";
cin >> a;
And in the terminal, the input request would look like this
please enter a value: _
How can I programatically simulate a user's typing in it.
Here's a sample how to manipulate cin's input buffer using the rdbuf() function, to retrieve fake input from a std::istringstream
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main() {
istringstream iss("1 a 1 b 4 a 4 b 9");
cin.rdbuf(iss.rdbuf()); // This line actually sets cin's input buffer
// to the same one as used in iss (namely the
// string data that was used to initialize it)
int num = 0;
char c;
while(cin >> num >> c || !cin.eof()) {
if(cin.fail()) {
cin.clear();
string dummy;
cin >> dummy;
continue;
}
cout << num << ", " << c << endl;
}
return 0;
}
See it working
Another option (closer to what Joachim Pileborg said in his comment IMHO), is to put your reading code into a separate function e.g.
int readIntFromStream(std::istream& input) {
int result = 0;
input >> result;
return result;
}
This enables you to have different calls for testing and production, like
// Testing code
std::istringstream iss("42");
int value = readIntFromStream(iss);
// Production code
int value = readIntFromStream(std::cin);
Hey why don't you write your input in a plain text file and redirect it to cin ???
It's the simplest method.
Open Command Prompt.
Suppose your text file which will used as input is in.txt and your program is prog.exe.
Keep the text file and the program in same folder. cd to your folder. Then type:
prog.exe < in.txt
Remember, your text file will be treated exactly as it is. Shoudld't be a problem if you know cin only catches upto next whitespace character, while string input functions (e.g. cin.getline) only catch upto next newline character.
//Sample prog.cpp
#include <iostream>
using namespace std;
int main()
{
int num;
do
{
cin >> num;
cout << (num + 1) << endl;
}
while (num != 0);
return 0;
}
//Sample in.txt
2
51
77
0
//Sample output
3
52
78
1
Sorry if you are on other platform, I don't know about them.

How to simulate user input in c++? [duplicate]

If we have this code snippet:
int a;
cout << "please enter a value: ";
cin >> a;
And in the terminal, the input request would look like this
please enter a value: _
How can I programatically simulate a user's typing in it.
Here's a sample how to manipulate cin's input buffer using the rdbuf() function, to retrieve fake input from a std::istringstream
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main() {
istringstream iss("1 a 1 b 4 a 4 b 9");
cin.rdbuf(iss.rdbuf()); // This line actually sets cin's input buffer
// to the same one as used in iss (namely the
// string data that was used to initialize it)
int num = 0;
char c;
while(cin >> num >> c || !cin.eof()) {
if(cin.fail()) {
cin.clear();
string dummy;
cin >> dummy;
continue;
}
cout << num << ", " << c << endl;
}
return 0;
}
See it working
Another option (closer to what Joachim Pileborg said in his comment IMHO), is to put your reading code into a separate function e.g.
int readIntFromStream(std::istream& input) {
int result = 0;
input >> result;
return result;
}
This enables you to have different calls for testing and production, like
// Testing code
std::istringstream iss("42");
int value = readIntFromStream(iss);
// Production code
int value = readIntFromStream(std::cin);
Hey why don't you write your input in a plain text file and redirect it to cin ???
It's the simplest method.
Open Command Prompt.
Suppose your text file which will used as input is in.txt and your program is prog.exe.
Keep the text file and the program in same folder. cd to your folder. Then type:
prog.exe < in.txt
Remember, your text file will be treated exactly as it is. Shoudld't be a problem if you know cin only catches upto next whitespace character, while string input functions (e.g. cin.getline) only catch upto next newline character.
//Sample prog.cpp
#include <iostream>
using namespace std;
int main()
{
int num;
do
{
cin >> num;
cout << (num + 1) << endl;
}
while (num != 0);
return 0;
}
//Sample in.txt
2
51
77
0
//Sample output
3
52
78
1
Sorry if you are on other platform, I don't know about them.

C++ : initialize input programmatically

If we have this code snippet:
int a;
cout << "please enter a value: ";
cin >> a;
And in the terminal, the input request would look like this
please enter a value: _
How can I programatically simulate a user's typing in it.
Here's a sample how to manipulate cin's input buffer using the rdbuf() function, to retrieve fake input from a std::istringstream
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main() {
istringstream iss("1 a 1 b 4 a 4 b 9");
cin.rdbuf(iss.rdbuf()); // This line actually sets cin's input buffer
// to the same one as used in iss (namely the
// string data that was used to initialize it)
int num = 0;
char c;
while(cin >> num >> c || !cin.eof()) {
if(cin.fail()) {
cin.clear();
string dummy;
cin >> dummy;
continue;
}
cout << num << ", " << c << endl;
}
return 0;
}
See it working
Another option (closer to what Joachim Pileborg said in his comment IMHO), is to put your reading code into a separate function e.g.
int readIntFromStream(std::istream& input) {
int result = 0;
input >> result;
return result;
}
This enables you to have different calls for testing and production, like
// Testing code
std::istringstream iss("42");
int value = readIntFromStream(iss);
// Production code
int value = readIntFromStream(std::cin);
Hey why don't you write your input in a plain text file and redirect it to cin ???
It's the simplest method.
Open Command Prompt.
Suppose your text file which will used as input is in.txt and your program is prog.exe.
Keep the text file and the program in same folder. cd to your folder. Then type:
prog.exe < in.txt
Remember, your text file will be treated exactly as it is. Shoudld't be a problem if you know cin only catches upto next whitespace character, while string input functions (e.g. cin.getline) only catch upto next newline character.
//Sample prog.cpp
#include <iostream>
using namespace std;
int main()
{
int num;
do
{
cin >> num;
cout << (num + 1) << endl;
}
while (num != 0);
return 0;
}
//Sample in.txt
2
51
77
0
//Sample output
3
52
78
1
Sorry if you are on other platform, I don't know about them.

C++ - Sanitize Integer Whole Number Input

I currently am using a function I found in another StackOverflow post(I can't find it), that I am using before, named "GetInt". My issue with it is that if the user inputs something like "2 2 2" it puts it into my next two Cin's. I have tried getLine, but it requires a string and I am looking for an int value. How would I structure a check to sanitize for an integer value greater than 2 and throw an error to the 2 2 2 answer.
#include <iostream>
#include <string>
#include <sstream>
#include "Board.cpp"
#include "Player.cpp"
using namespace std;
int getInt()
{
int x = 0;
while (!( cin >> x))
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Please input a proper 'whole' number: " << endl;
}
return (x);
}
and my call
do
{
//do
//{
cout << "How many players are there? \n";
numberOfPlayers = getInt();
//} while (isdigit(numberOfPlayers) == false);
} while (numberOfPlayers < 2);
EDIT:
I chose Justin's answer because it was the closest to my original code and solved the issue without major changes.
Integers are delimited by spaces and the input 2 2 2 is just multiple integers. If you want to make sure that just one integer is entered per line you could skip whitespace characters until a newline is found. If a non-whitespace is found prior to a newline you could issue an error:
numberOfPlayers = getInt();
int c;
while (std::isspace(c = std::cin.peek()) && c != '\n') {
std::cin.ignore();
}
if (c != std::char_traits<char>::eof() && c != '\n') {
// deal with additional input on the same line here
}
You were on the right track with std::getline. You read the whole line as a string, then put it into a std::istringstream and read the integer out.
std::string line;
if( std::getline(cin, line) ) {
std::istringstream iss(line);
int x;
if( iss >> x ) return x;
}
// Error
This will have the effect of discarding any fluff that comes after the integer. It will only error if there is no input or no integer could be read.
If you want to have an error when stuff appears after the integer, you could take advantage of the way strings are read from a stream. Any whitespace is okay, but anything else is an error:
std::istringstream iss(line);
int x;
if( iss >> x ) {
std::string fluff;
if( iss >> fluff ) {
// Error
} else {
return x;
}
}
Change your code to this:
int getInt()
{
int x = 0;
while (!( cin >> x))
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Please input a proper 'whole' number: " << endl;
}
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
return (x);
}
Your code to ignore the rest of the line after receiving the integer is only called if the integer collection fails (for example, you type "h" as the number of players).