How can I get 3 numbers at once from a user in the command prompt so that I can perform a dot-product operation on it with an existing array? For example:
suppose in advance, I define
int myArray[3] = {1,2,3};
Now a user enters natural numbers in the format "i,j,k".
The program spits out
myArray[0]*userArray[0] + myArray[1]*userArray[1] + myArray[2]*userArray[2]
that is,
1*a + 2*b + 3*c
I was able to do exactly this with predefined arrays, easily. However, something is going terribly wrong when I try to identify the user input as pieces of an array. The program thinks the numbers are different or in a different place, or of a different structure, resulting in negative or humongous answers.
[Part of] My program is below. The goal is the same as the example:
#include "stdafx.h"
#include <cstdlib>
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <limits>
#include <tuple>
int main()
{
int nNumCup = 0, nNumLem = 0, nNumSug = 0, nNumIce = 0;
float fCoH = 20.00, fCostCup25 = 1.99, fCostCup50 = 2.49, fCostCup100 = 2.99;
int arrnStoreInput01A[3];
std::cout << "Go to Cups \n \n";
std::cout << "Cups are availible in packs of 25, 50 and 100. \n"
"Please enter three numbers in \"i,j,k\" format for the \n"
"respective amounts of each of the following three products \n"
"you want to buy: \n \n"
"A) 25-pack of cups for " << fCostCup25 << "\n"
"B) 50-pack of cups for " << fCostCup50 << "\n"
"C) 100-pack of cups for " << fCostCup100 << "\n \n"
"For example, type \"0,4,0\" to purchase 4 packages of 50 cups or \n"
"type \"3,2,1\" to buy 3 packages of 25 cups, 2 packages of 50 cups \n"
"and 1 package of 100 cups. \n \n";
//This is where the user inputs "i,j,k". I entered "3,2,1" in the command prompt.
std::cin >> arrnStoreInput01A[0] >> arrnStoreInput01A[1] >> arrnStoreInput01A[2];
float arrnCostCup[3] = { fCostCup25,fCostCup50,fCostCup100 };
float fStoreInput01AdotfCoH = arrnStoreInput01A[0] * arrnCostCup[0]
+ arrnStoreInput01A[1] * arrnCostCup[1]
+ arrnStoreInput01A[2] * arrnCostCup[2];
int arrnQuantCup[3] = { 25,50,100 };
if (fStoreInput01AdotfCoH <= fCoH){
fCoH = fCoH - fStoreInput01AdotfCoH;
nNumCup = nNumCup + arrnStoreInput01A[0] * arrnQuantCup[0]
+ arrnStoreInput01A[1] * arrnQuantCup[1]
+ arrnStoreInput01A[2] * arrnQuantCup[2];
}
else
std::cout << "Not enough cash on hand.";
std::cout << "you have " << nNumCup << " cups! \n";
std::cout << "you have " << fCoH << " left in cash!";
//Inspecting what the program thinks the user-inputed array is
//(next lines) reveals that it is interpreting "3,2,1"
//erroneously as 3 -858993460 -858993460
for (auto const value : arrnStoreInput01A)
{
std::cout << value << ' ';
}
return 0;
}
I am also attaching a picture of the command prompt output because that is very illustrative and arguably easier to interpret (see top of post).
use a for loop to store the user input on the array. When the user finishes, then you do the operation. Something like this:
#include <iostream>
#include <vector>
int main()
{
std::vector<int> userInput ;
std::vector<int> predefinedArray{1,2,3};
for(int i=0;i<3;i++)
{
int tmp;
std::cout<< "Introduce input numer " <<i<<": " ;
std::cin >> tmp;
userInput.push_back(tmp);
}
std::cout<<userInput[0]*predefinedArray[0]+
userInput[1]*predefinedArray[1]+
userInput[2]*predefinedArray[2]<<std::endl;
return 0;
}
I would recomend you to use std::vector as I did on the above code.
Have a look at how operator>> works. It reads integers up to the comma (or anything not an integer). You will have to remove the comma from the input stream to get the next number.
You could use ignore:
std::cin >> arrnStoreInput01A[0];
std::cin.ignore(1,',');
std::cin >> arrnStoreInput01A[1];
std::cin.ignore(1,',');
std::cin >> arrnStoreInput01A[2];
Related
Edited -- See below for new info........ I'm new to programming - C++ - and was on Codingame where I ran in to a problem I can't find the answer for...
We were given two strings -- not char array which I expected and seems many of the answers I found on the web expected too -- and were expected to combine them in to one.
Example:
string1 = 01101
string2 = 01001
Answer = 01001
I have learned and understand how the answer is derived but I can't figure out the C++ code for it.
Any help would be great!
Thank you!
Thanks to nicomp I now know the correct terms are bitwise AND, not binary merge.
I was able to get a little further but still having issues getting the answer. I took the following code and got the output of 73.
#include <iostream>
#include <bitset>
#include <string>
using namespace std;
int main()
{
string str1 = "001101";
string str2 = "011001";
int a = stoi(str1);
cout << a << endl;
int b = stoi(str2);
cout << b << endl;
int c = a & b;
cout << c << endl;
return 0;
}
The result I should get is:
string str1 = "001101";
string str2 = "011001";
Answer = "001001";
or I would have settled for 9 since that is the non-binary value, not 73.
Can someone help me progress with this?
Thanks again!
int a = 0b01101
int b = 0b01001
int c = a & b;
You can convert a binary string to int like this:
std::string str = "1101";
int num = std::stoi("01010", 0, 2);
It's not 100% what I was looking for, but it does do what I wanted. The one part I would say isn't to my expectation is that I convert the numbers to decimal rather than leaving everything in binary. Regardless... this does take in two binary numbers and outputs one binary number after ANDing.
#include <iostream>
#include <bitset>
#include <string>
using namespace std;
int main()
{
string input1 = " ";
string input2 = " ";
cout << "Enter first binary number: " << endl;
cin >> input1;
cout << "Enter second binary number: " << endl;
cin >> input2;
int a = (int)bitset<64>(input1).to_ulong();
cout << a << endl;
int b = (int)bitset<64>(input2).to_ulong();
cout << b << endl;
int c = a & b;
cout << c << endl;
string output = bitset<8>(c).to_string();
cout << output << endl;
return 0;
}
So as the title describes I'm trying to learn PRNG but it hasn't gone too well thusfar. I am writing a program that takes an entered number of choices, rolls a dice and makes the choice for you. I do this using rand() and an array of strings with a length that is dependant on a variable read in before the declaration of the array.
The two problems showing up are that if I try to choose between for example 12 choices, the program will crash. As I read in the length of the array before I declare it I don't understand how this could happen. Also the PRNG will always return the number 2 which is not the desired function of a function that should return a random number between min and max. I will share my code below:
#include <iostream>
#include <cstdlib> // for rand() and srand()
#include <ctime> // for time()
#include <string>
using namespace std;
int callPRNG(int min, int max)
{
srand(static_cast<unsigned int>(time(0))); // set initial seed value to system clock
static const double fraction = 1.0 / (static_cast<double>(RAND_MAX) + 1.0); // static used for efficiency, so we only calculate this value once
// evenly distribute the random number across our range
return static_cast<int>(rand() * fraction * (max - min + 1) + min);
}
int main()
{
int max=1;
int min=0;
cout << "Please enter the amount of choices you want to choose from: ";
cin >> max;
string choices[max-1];
int choiceMade=0;
{
int i=0;
while(i<=max-1)
{
cout << "Please enter choice " << i+1 << ": ";
cin >> choices[i];
i++;
}
choiceMade=callPRNG(min, max-1);
cout << "I have decided: " << choices[choiceMade-1];
}
return 0;
}
As extra information, I'm using code::blocks with C++11 enabled on a windows 10 OS. I hope someone can help me with this as I don't quite understand arrays and PRNG well enough to find the error by myself. Thanks :)
edit: It seems, as I can now use higher values for max without crashing the program, that the answer scales with the value of max.
The problem with crashing is because you're not allocating enough space for the array of choices (you need the size to be max, not max - 1). You're using a G++ extension to C++ — namely variable length arrays — which are part of standard C but not standard C++. You should use a vector of strings.
The non-random random behaviour is more a reflection on the quality of the rand() PRNG — it is often not very good. I was getting similar behaviour on macOS Sierra 10.12.2 with G++ 6.3.0. I worked around it by avoiding the use of floating point arithmetic and using modulus operations.
The use of choiceMade-1 was suspect too; given a choice of 0, it tries to access non-existent element -1 of the array of choices.
These changes yield the following code, which still has debug code in place:
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
#include <vector>
using namespace std;
int callPRNG(int min, int max)
{
cout << __func__ << ": " << min << " .. " << max << "\n";
unsigned int seed = static_cast < unsigned int > (time(0));
cout << __func__ << ": " << seed << "\n";
srand(seed);
int range = max - min + 1;
int max_valid = RAND_MAX - RAND_MAX % range;
int rand_val;
while ((rand_val = rand()) > max_valid)
;
int rv = rand_val % range;
cout << __func__ << ", rand_val = " << rand_val << ", ret_val = " << rv << "\n";
return rv;
}
int main()
{
int max = 1;
int min = 0;
cout << "Please enter the amount of choices you want to choose from: ";
cin >> max;
vector < string > choices(max);
int choiceMade = 0;
int i = 0;
while (i <= max - 1)
{
cout << "Please enter choice " << i + 1 << ": ";
cin >> choices[i];
i++;
}
choiceMade = callPRNG(min, max - 1);
cout << "I have decided: " << choices[choiceMade] << endl;
return 0;
}
Sample outputs:
Please enter the amount of choices you want to choose from: 12
Please enter choice 1: a
Please enter choice 2: b
Please enter choice 3: c
Please enter choice 4: d
Please enter choice 5: e
Please enter choice 6: f
Please enter choice 7: g
Please enter choice 8: h
Please enter choice 9: i
Please enter choice 10: j
Please enter choice 11: k
Please enter choice 12: l
callPRNG: 0 .. 11
callPRNG: 1483236759
callPRNG, rand_val = 770034137, ret_val = 5
I have decided: f
Over a series of runs, with filtering out all except the 'I have decided' lines, I got outputs:
I have decided: g
I have decided: i
I have decided: d
I have decided: f
I have decided: a
I have decided: c
I have decided: l
I have decided: f
I have decided: a
I have decided: f
I have decided: h
Jonathan Leffler's answer was complete and correct. But I thought you might also be interested in a shorter program that uses <random>:
#include <vector>
#include <iostream>
#include <string>
#include <random>
size_t callRNG(size_t min, size_t max)
{
std::random_device r{};
std::uniform_int_distribution<size_t> ud{min,max};
return ud(r);
}
int main()
{
const auto min{0};
std::vector<std::string> choices{};
std::string line{};
while(std::cout << "Please enter choice: ", std::getline(std::cin, line) && !line.empty()) {
choices.push_back(line);
}
const auto max{choices.size() - 1};
if(!choices.empty()) {
std::cout << "I have decided: " << choices[callRNG(min, max)] << '\n';
}
}
We're learning about stringstream and finput in class and I am confused about the values I am getting for this code:
Source Code:
#include <iostream>
#include <fstream>
#include <sstream>
#include <iomanip>
using namespace std;
main() {
ifstream finput("input.txt"); // Read File
string line, name; // Declare variable line and name
int value = 0, total = 0, count = 0; // Declare variable value, total, and count
while (!finput.eof()) { // While the end of file has not been reached
getline(finput, line ); // Get the entire first line of the file and set it to line variable
istringstream istr(line); // Convert to parsed string
istr >> name; // first line of str is converted to the name
while (istr >> value) { // while there are remaining integer values to output
total += value; // Add value to total
count++; // add 1 to count
}
cout << name << " " << total << fixed << setprecision(1) << total * 1.0 / count << endl;
}
}
And here is my input file:
Thomas 1
Jack 1 3
Jim 1 2 3
And here is my output:
Thomas 11.0
Jack 51.7
Jim 111.8
Jim 111.8
Process returned 0 (0x0) execution time : 0.016 s
Press any key to continue.
Why am I not getting "Thomas 1", "Jack 2", and "Jim 2"? And why is Jim displaying twice? My professor did not explain very well what exactly stringstream did and how it works.
I would really appreciate the help. Thanks!
1.
You don't initialize the values of total and count so they only grow; declare
int value = 0, total = 0, count = 0;
inside the loop that reads from file.
2.
You don't output space between the printed values; use
cout << name << " " << total << " " << fixed << setprecision(1) << total * 1.0 / count << endl;
when outputting.
This question already has answers here:
How do I iterate over the words of a string?
(84 answers)
Closed 8 years ago.
I have a weird problem, so my instructor told us to create a simple program using vectors that will first ask the user how many integers they want to enter, and after the numbers were entered via a space as a delimiter the output should add 2 to each vector element.
Ex -
How many numbers are you going to enter = 4 (Lets assume the user enters 4)
Enter the numbers = 11 45 71 24 (Lets assume the user entered these 4 numbers)
THE OUTPUT SHOULD BE THIS = 13 47 73 26 (with spaces added 2)
Since using vectors is a must, i know how to add add 2 with a normal integer vector output but when it comes with spaces i have no idea, so far the program i wrote will accept everything before the space into the vector and will add 2 to it.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
vector <int> userInput;
int input;
int number;
int num1;
cout << "How many numbers are you going to enter ? :";
cin >> number;
cout << "Enter the Numbers : " << endl;
cin >> input;
userInput.push_back(input);
cout << "Vector Contains : ";
for (unsigned int i = 0; i < userInput.size(); i++)
{
cout << userInput[i] + 2;
}
system("pause>nul");
return 0;
}
The reason you're only taking in one input is because you're only taking in one int from std::cin. The other ints are still remaining in the stream. You should do this:
while(/*we still have stuff to extract*/)
{
std::cin >> input;
userInput.push_back(input);
}
However, we still need to know when to stop. Since we're only expecting one line of input from the user, we can do std::cin.peek() != '\n' to check if we've reached the point where the user pressed the Enter key earlier.
Thank you for reading.
The standard extraction operator for int expects whitespace as the separator between items so you don't need to do anything special there. Just read ints, put them in your vector, do the addition, and print out the results. Assuming you've already read n for the count, the real work could look something like this:
std::copy_n (std::istream_iterator<int>(std::cin),
n,
std::back_inserter(your_vector));
std::transform(your_vector.begin(), your_vector.end(),
std::ostream_iterator<int>(std::cout, " "),
[](int i){ return i + 2; });
Try the following
#include <iostream>
#include <vector>
#include <cstdlib>
int main()
{
std::cout << "How many numbers are you going to enter ? :";
size_t n = 0;
std::cin >> n;
std::vector<int> v( n );
std::cout << "Enter " << n << " numbers : " << std::endl;
int x;
for ( size_t i = 0; i < n && std::cin >> x; i++ ) v[i] = x;
for ( int x : v ) std::cout << x + 2 << ' ';
std::cout << std::endl;
std::system( "pause>nul" );
return 0;
}
If to input
4
11 45 71 24
the output will be
13 47 73 26
Other approach is to use standard function std::getline and std::istringstream instead of the operator >>
For example
#include <iostream>
#include <vector>
#include <cstdlib>
#include <string>
#include <sstream>
#include <limits>
int main()
{
std::cout << "How many numbers are you going to enter ? :";
size_t n = 0;
std::cin >> n;
std::vector<int> v( n );
std::cout << "Enter " << n << " numbers : " << std::endl;
std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
std::string s;
std::getline( std::cin, s );
std::istringstream is( s );
int x;
for ( size_t i = 0; i < n && is >> x; i++ ) v[i] = x;
for ( int x : v ) std::cout << x + 2 << ' ';
std::cout << std::endl;
std::system( "pause>nul" );
return 0;
}
I need to turn user input (a number) into an output of TAB spaces.
Example I ask user:
cout << "Enter amount of spaces you would like (integer)" << endl;
cin >> n;
the (n) i need to turn it into an output like:
cout << n , endl;
and what prints on the screen would be the spaces
ex
input is 5
out put |_| <~~~there are five spaces there.
Sorry If I can't be clear, probably this is the reason I haven't been able to find an answer looking through other people's questions.
any help will be greatly appreciated.
Just use std::string:
std::cout << std::string( n, ' ' );
In many cases, however, depending on what comes next, is may be
simpler to just add n to the parameter to an std::setw.
cout << "Enter amount of spaces you would like (integer)" << endl;
cin >> n;
//print n spaces
for (int i = 0; i < n; ++i)
{
cout << " " ;
}
cout <<endl;
You just need a loop that iterates the number of times given by n and prints a space each time. This would do:
while (n--) {
std::cout << ' ';
}
I just happened to look for something similar and came up with this:
std::cout << std::setfill(' ') << std::setw(n) << ' ';
You can use C++ manipulator setw(n) function which stands for set width to print n spaces.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int n;
std::cin>>n;
cout<<"Here is "<<n <<" spaces "<<setw(n)<<":";
}
And don't forget to include C++ Library -
enter image description here
Appending single space to output file with stream variable.
// declare output file stream varaible and open file
ofstream fout;
fout.open("flux_capacitor.txt");
fout << var << " ";
Simply add spaces for { 2 3 4 5 6 } like these:
cout<<"{";
for(){
cout<<" "<<n; //n is the element to print !
}
cout<<" }";