How can I get specified number?
For example, the number that a user enters is 4568962358.
I want to save the "96" in a variable; how do I get just the 96 or 23?
This is the real problem:
An important shipping company is making the annual inventory of the goods they have in their warehouse, for which they have implemented a system of codes that are assigned to each good that is in said warehouse. This code, which consists of 16 digits, contains the following information: unique number, indicator of whether it is fragile or not, place of origin of the property and expiration date of the property.
The assigned code structure is UUUFPPPPDDMMAAAA where:
UUU: unique number of the good.
F: digit that indicates if the good is fragile or not. If it is 0 it means that it is fragile.
PPPP: ASCII codes of the two letters that identify the country of origin of the good.
DD: Good's due date.
MM: Month of the expiration of the good.
AAAA: Year of expiration of the good.
You are asked to create a C ++ program that receives the assigned code as data and then prints the following data as shown in the example.
Enter the code: 1120677212042015
Then the program must print: Unique number: 112.
Fragile(N: No; S: Yes): S .
Country of origin: CH .
Day, month and year of expiration: 04-12-2015 .
Well it is outdated to date (N : No; S: Yes): S.
In the solution of the problem you will not be able to make use of selective structures.
Version 1
#include "stdafx.h"
#include "conio.h"
#include "iostream"
using namespace System;
using namespace std;
int main()
{
int code;
int UUU;
int F;
int PP1,PP2;
int DD;
int MM;
int AAAA;
cout << "Enter the code: "; cin >> code; // 1120677212042015
// ...code needed here
UUU = int(code / 10000000000000);
cout << "\nRESULTS" << endl;
cout << "\nUnique number: " << UUU << endl; // prints 112
_getch();
return 0;
}
Version 2
I'm not able to do the next parts; please help!
#include "stdafx.h"
#include "conio.h"
#include "iostream"
using namespace System;
using namespace std;
int main()
{
double code;
double UUU;
double F;
double PP1,PP2;
double DD;
double MM;
double AAAA;
cout << "Enter the code: "; cin >> code; // 1120677212042015
UUU = int(code / 10000000000000);
PP1 = int(code / 10000000000) % 100;
PP2 = int(code / 100000000) % 100;
DD = int(code / 1000000) % 100;
cout << "\nRESULTS" << endl;
cout << "\nUnique number: " << UUU << endl; // 112
cout << "Country of origin: " << (char)PP1 << (char)PP2<<endl; //CH
cout << "Day, Month and Year of expiration: " << DD; // 12/../....
_getch();
return 0;
}
One way is using substr concept.
For example, if user enters input as 1120677212042015, then read it into a string and divide the string into sub-strings according to the format UUUFPPPPDDMMAAAA .
std::string sUserCode = "1120677212042015";
std::string sUniqueNumber = str.substr (0,3);
int iUniqueNumber = stoi(sUniqueNumber);
This is one of those occasions where the C library comes in handy :
int UUU, F, PP1, PP2, DD, MM, AAAA;
cout << "Enter the code: "; // 1120677212042015
scanf("%3d %1d %2d %2d %2d %2d %4d", &UUU, &F, &PP1, &PP2, &DD, &MM, &AAAA);
This captures all the values. The spaces in the format string are not necessary, but makes it easier to read.
u can use % and / to do this
4568962358 / 10000 = 456896 %100 = 96
or you can put it in a array and show the part of integer that u want.
int n = 4568962358;
int a[10];
for (int i = 0; i<10 ; i++)
{
a[i] = n%10;
n /= 10;
}
search your question in stack over flow.
these questions have good answers.
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;
}
I am new to C++, trying to import dates into a program, adding up digits of day, month, year resp and writing back to txt.
input data
sl.no name day month year
1 Rob 15 05 2019
2 Tim 12 06 2002
Desired output data in txt
sl.no name day month year
1 Rob 6 5 3
2 Tim 3 6 4
I have been able to import data from a txt file and also add the digits in day but it does not repeat forward. what am i doing wrong ?
sample code
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream theFile("data.txt");
int id,day,month,year,daysum=0,monthsum=0, yearsum=0;
string name;
while (theFile >> id >> name >> day >> month >> year)
{
cout << id << ", "<< name <<", "<< day<<", "<<month <<", "<< year<<","<< endl;
}
while (day > 0)
{
daysum = daysum + (day % 10);
day = day / 10;
cout << daysum << endl;
}
I am no expert . but have been in your spot a few months ago.. break down the problem into smaller steps..
My approach..
Pseudo Code:
Ditch the header
Create a function for adding the digits
Read data from file
Use a loop to run through each element of the every column and use the function created
Store results in a variable
Output variable to a new text file
comment if there is a specific area where you are stuck..
Try this to reduce it to single digits.. knit to other parts of your code..
#include <iostream>
using namespace std;
int main()
{
long long num;
cout << "Enter a number: ";
cin >> num;
int sum = 0;
while (1)
{
sum += (num % 10);
num /= 10;
if (0 == num)
{
if (sum > 9)
{
num = sum;
sum = 0;
}
else
{
cout << "Answer: ";
cout << sum << endl;
return 0;
}
}
};
return 0;
}
you are reading the file and data wrong,
you need to discard the header (sl.no name day month year)
and then accumulate the daysum while reading the file progressively one row after the other until the end...
Before I ask anything, I should mention that I have a shaky foundation in C++. Let me know if I'm not being clear on anything and I will do my best to clarify.
My coding problem here is reading a series of 24-hour time values, with no seconds included, and storing them into an array of a structure. Reading the hours and minutes in integer format, and storing it into an array of structures is what I'm not understanding with this. In the text file, the first number in each row is the 24-hour time, and the second number is the amount of minutes that I need to modify the time with. I'm stuck frozen at just reading the times in to begin with.
This is the code I have so far.This is the result of the code.
#include <iostream>
#include <fstream>
using namespace std;
int main(){
int size = 7;
int i;
struct Times {
int T;
int M;
};
Times clock[7];
ifstream infile;
infile.open("times.txt");
for (i=0; i<size; i++){
infile>>clock[i].T>>clock[i].M;
}
for (i=0; i<size; i++){
cout<<clock[i].T << " "
<<clock[i].M <<endl;
}
}
Here is the contents of the text file:
6:45 39
12:00 73
0:00 4
23:59 1
22:45 70
11:59 1
14:15 95
Here is the updated code which seems to work:
#include <iostream>
#include <fstream>
using namespace std;
int main(){
int size = 7;
int i;
char colon;
struct Times {
int hour;
int minute;
int M;
};
Times clock[7];
ifstream infile;
infile.open("times.txt");
for (i=0; i<size; i++){
infile>>clock[i].hour>>colon>>clock[i].minute>>clock[i].M;
}
for (i=0; i<size; i++){
cout<<clock[i].hour << " "
<<colon << " "
<<clock[i].minute << " "
<<clock[i].M
<<endl;
}
}
Note that each line of your file contains three integral values, not two, and that a colon will stop reading in an integral value (formatted input for integrals will skip leading white spaces and even new line characters, but not "leading" colons). If you want to read an integral value that follows a colon, you'll need to skip the colon.
You could do this by reading in the colon into a variable of type char (and ignoring it afterwards). The code could look as follows:
int main()
{
int hour,minute,x;
char colon;
stringstream s { "15:43 10\n16:48 20\n" };
while (s >> hour >> colon >> minute >> x) {
cout << "H:M=" << hour << ":" << minute << "; times=" << x << std::endl;
}
}
Output:
H:M=15:43; times=10
H:M=16:48; times=20
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];
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';
}
}