I wanted to take an input char and then from that get a predefined number which was assigned to the char.
Example
int A=100;
char in;
cin>>in; //input A;
and then use that in char to identify with A and pass the value it holds.
sorry if i am not that clear.
As mentioned in a comment on your question, you'd want to use a map
#include <map>
...
std::map<char, int> char_map = {
{'A', 100}
};
char in;
std::cin >> in; //input A;
std::cout << char_map[in] << std::endl;
Of course you would probably need to add some form of verification on the key.
Simple example
#include <iostream>
#include <unordered_map>
int main(void)
{
char c;
std::unordered_map<char, int> uMap;
for (int i = 'A'; i <= 'Z'; i++)
{
uMap[i] = i - 'A' + 1;
}
c = fgetc(stdin);
std::cout << "\nCharacter '" << c << "' has value " << uMap[c];
return 0;
}
Input
1. A
2. C
3. Z
Output
1. Character 'A' has value 100
2. Character 'C' has value 102
3. Character 'Z' has value 125
your input is a char so you can compare it against some other chars too
char input;
std::cin >> input; //input A;
std::cout << "input: " << input << std::endl;
if (input == 'A')
{
std::cout << "input was A: " << std::endl;
}
else
{
std::cout << "input was not: " << std::endl;
}
Related
I have a character array that produces a random array of lowercase letters in the length that the user inputs. my problem is that after the array of random letters is produced the user inputs a pair of charaters(two letters) and my code should check if that pair is in the random array that was produced. it worked fine when it just checked for one letter but when i introduced the second one it does not work.I would appreciate any help.
#include <ctime>
#include <iostream>
#include <cstdlib>
int main() {
std::srand(std::time(NULL));
int i, num;
char letter1, letter2, ch, r;
const char chars[]="abcdefghijklmnopqrstuvwxyz";
std::cout << "How many letters do you want in your string? ";
std::cin >> num;
for (i=0; i<num; i++)
{
ch = chars[rand()%26];
std::cout << ch;
}
std::cout << "\nWhat letter pair would you like to find? ";
std::cin >> letter1 >> letter2;
if ((chars[i] == letter1) && (chars[i+1]==letter2))
std::cout << "It is in your string. ";
else
std::cout << "You do not have " << letter1 << letter2 << " in your string";
}
First, you are not storing your randomly generated chars
for (i=0; i<num; i++)
{
ch = chars[rand()%26];
std::cout << ch;
}
This just writes a random char in ch and displays it on the console with each iteration. You don't store your data, ch just contains the last random char after your loop ends and everything else is lost.
The part where you want to search is double wrong.
if ((chars[i] == letter1) && (chars[i+1]==letter2))
std::cout << "It is in your string. ";
else
std::cout << "You do not have " << letter1 << letter2 << " in your string";
This isn't inside a loop, i is simply always going to be num-1.
The array you are checking is chars which is your const array containing "abcdefghijklmnopqrstuvwxyz". This doesn't contain your randomly generated chars.
I cannot figure out why my getchar() function is not working the way I want it to work. I am getting 10 not 2. Please take a look.
Main():
#include <cstdlib>
#include <iostream>
#include <fstream>
using namespace std;
int main() {
int var, newvar;
cout << "enter a number:" << endl;
cin >> var;
newvar = getchar();
cout << newvar;
return 0;
}
Here is my output:
enter a number:
220
10
Ultimately though I need to be able to distinguish between a '+' '-' or letter or number.
This is maybe not the cleanest way to do it but you can get every char one by one :
#include <iostream>
using namespace std;
int main()
{
int var;
cout << "enter a number:" << endl;
cin >> var;
std::string str = to_string(var);
for(int i=0; i < str.length();++i)
cout << str.c_str()[i] << endl;
return 0;
}
If you enter for example: "250e5" it will get only 250 and skip the last 5.
Edit:
This is just a simple parser and does not do any logic.
If you want to make a calculator I would recommend you to look at what Stroustrup did in his book the c++ programming language.
int main()
{
string str;
cout << "enter a number:" << endl;
cin >> str;
for(int i=0; i < str.length();++i) {
char c = str.c_str()[i];
if(c >= '0' && c <= '9') {
int number = c - '0';
cout << number << endl;
}
else if(c == '+') {
// do what you want with +
cout << "got a +" << endl;
} else if(c == '-')
{
// do what you want with -
cout << "got a -" << endl;
}
}
return 0;
}
I was trying to make letters into numbers in c++. When I write in console it should count modulo and type out if ship is coming (i did all, but can't make letters into numbers :/ )
This what should happen: ABC a = 1; b=2; c=3 1*2*3=6....
So I need to write a word and it should be separated into letters and converted into numbers like that.
I am just learning and I don't know much :)
My current code:
int shipnum, groupnum, moduleship, modulegroup;
cout << "type ship number "; cin >> shipnum;
cout << "type group number "; cin >> groupnum;
/*shipnum dabar 5... (5 mod 2)
groupnum dabar 3... (3 mod 2)
*/
moduleship = shipnum % 47; //skaiciuojam moduli...
modulegroup = groupnum % 47;
if (moduleship == modulegroup) {
cout << "YES ship is coming for you :)";
}
else if (moduleship != modulegroup) { // "!=" reiskia "nelygu"
cout << "SORRY, NO ship for you :(";
}
return 0;
Your question isn't precise, although I find it enough. Tip: Be precise with the information you provide, there's no need to show the rest of the code.
Lets say we have this char Ship[20]="ABCDEF";. If you encoding is as simple as A=1, B=2, etc, then you only need something like this:
char Ship[20]="ABCDEF";
int decoded=1;
for(int i=1; Ship[i]=!'/0'; ++i) {
decoded = decoded * i
}
cout<<decoded;
This loop will run till it encounters the '\0' (null character) at the end of the string. So, you would have a factorial on the fact that your codeing (A=1,B=2, etc) represents a factorial.
otherwise, you could use a switch case, or if statements to check for individual characters and decode appropriately.
char Ship[20]="ABCDEF";
int decoded=1;
for(int i=1; Ship[i]=!'/0'; ++i) {
switch(Ship[i]){
case 'A' : decoded = decoded * 1;
break;
case 'B' : decoded = decoded *2;
break;
//So on
default : break;
}
}
cout<<decoded;
Output in both cases:
720
"convert letters into numbers (A=1; B=2…)"
string a{"ABC"};
int a0 = a[0]; // 65
int a1 = a[1]; // 66
int a2 = a[2]; // 67
.....
want to wrap A = 1, B = 2...
a0 = a0 - (65 - 1);
a1 = a1 - (65 - 1);
....
The question is not clear but i think the question basically is to convert char into int which follows the encoding A=1, B=2, ......, Z=26 and do the required processing which is to multiply all the encodings.
So here is how you could do it:
#include <iostream>
#include <string>
using namespace std;
int main(){
string s; //Input string
cout << "enter the string(CAPITALS ONLY) :";
cin >> s; //read the input string
int result = 1;
for (auto &elem : s){ //process all the characters of s
result *= elem - 'A' + 1; //corresponding int value is multiplied to the result
}
cout << "the result is :" << result;
}
Sample Output:
enter the string(CAPITALS ONLY) :AEF
the result is :30
(a+b)2=a2+b2+2ab: in cpp example
#include<iostream>
using namespace std;
//Declaring Function in scope
void firstFormula();
int main(void) //Main function
{
cout << "Hello World!!" << endl; //sample test text printing
firstFormula(); //executing function
return 0;
}
//function implementation
void firstFormula(){
//initializing variables
int a, b;
cout << "Enter Value of A" << endl;
cin >> a;//updating input values of a
cout << "Enter Value of B" << endl;
cin >> b;//updating input values of b
int v1 = a + b; //(a+b)2
int v2 = v1 * v1; //L.H.S
cout << "Value of v1=" << v1 << endl << "V2=" << v2 << endl;
cout << "Value of a=" << a << endl << "Value of B=" << b << endl;
int v3 = a * a;
int v4 = b * b;
int v5 = 2 * a * b;
int v6 = v3 + v4 + v5; //` R.H.S value after equation` `egfyufe`
cout << "Output=" << "V3=" << v3 << endl << "V4=" << v4 << endl << "v5="
<< v5 << endl << "V6=" << v6 << endl;
} //end
int countChars(string str)
{
int count = 0;
if (str == "")
return count;
else
{
count++;// add a character to the count
return count + countChars(str.substr(1));// function calls itself
}
}
I need to take the above function and call in in the program below and I'm not sure how to initialize it properly. Below is what I tried and it doesn't work. I'm not allowed to use the .length() because otherwise the program would be done.
int main()
{
char find = '\0';
string str;
int count = 0;
int length = int(countChars);
//ask the user for a sentence
cout << "Enter a sentence " << endl;
getline(cin, str);
//ask the user which letter they want the count of
cout << "Which letter would you like to find the number of appearances: " << endl;
cin >> find;
for (int i = 0; i < length; i++)
{
if (str[i] == find)
{
count++;
}
}
cout << "the letter " << find << " appears " << length << " times " << endl;
//waits for user to exit
system("pause");
cin.get();
}
It seems the function should count the number of appearances of a letter in a string. If so then it is declared and defined incorrectly. It has to have at least two parameters an object of type std::string and an object of type char.
Here is shown how such a recursive function can look
#include <iostream>
#include <string>
size_t countChars( const std::string &s, char c )
{
return s.empty() ? 0 : ( s[0] == c ) + countChars( { s, 1 }, c );
}
int main()
{
std::cout << "Enter a sentence ";
std::string s;
std::getline( std::cin, s );
std::cout << "Which letter would you like to find the number of appearances: ";
char c = '\0';
std::cin >> c;
std::cout << "The letter " << c
<< " appears " << countChars( s, c )
<< " times " << std::endl;
return 0;
}
The program output might look like
Enter a sentence My name is Alycia
Which letter would you like to find the number of appearances: a
The letter a appears 2 times
If you mean a function that just calculates the length of a string then it can look like
size_t countChars( const std::string &s )
{
return s.empty() ? 0 : 1 + countChars( { s, 1 } );
}
and shall be called after the statement
getline(cin, str);
I'm needing help in adding commas to the number the user enters, some guidance or help would be appreciated. So far I have it where i store the first three digits and the last six digits and then simply format it.
#include<iostream>
using namespace std;
int main ( int argc, char * argv[] )
{
unsigned long long userInput;
int fthreeDigit;
cout << "Enter a long long number: " << endl;
cin >> userInput;
fthreeDigit = ( userInput / 1000 );
userInput %= 1000;
cout << "Your Number: " << fthreeDigit << "," << userInput << endl;
system("pause");
return 0;
}
Is this what you need? The locale will do this for you correctly.
#include <iostream>
using namespace std;
int main ( int argc, char * argv[] )
{
unsigned long long userInput;
int fthreeDigit;
cout << "Enter a long long number: " << endl;
cin >> userInput;
std::cout.imbue(std::locale(""));
std::cout << userInput << std::endl;
return 0;
}
EDIT:
I have two solutions. first without playing with numbers (recommended) and second (division).
first solution is:
#include <cstdlib>
#include <iostream>
#include <locale>
#include <string>
using namespace std;
struct my_facet : public std::numpunct<char>{
explicit my_facet(size_t refs = 0) : std::numpunct<char>(refs) {}
virtual char do_thousands_sep() const { return ','; }
virtual std::string do_grouping() const { return "\003"; }
};
/*
*
*/
int main(int argc, char** argv) {
cout<<"before. number 5000000: "<<5000000<<endl;
std::locale global;
std::locale withgroupings(global, new my_facet);
std::locale was = std::cout.imbue(withgroupings);
cout<<"after. number 5000000: "<<5000000<<endl;
std::cout.imbue(was);
cout<<"and again as before. number 5000000: "<<5000000<<endl;
return 0;
}
before. number 5000000: 5000000
after. number 5000000: 5,000,000
and again as before. number 5000000: 5000000
RUN SUCCESSFUL (total time: 54ms)
and second (not recommended) is :
double f = 23.43;
std::string f_str = std::to_string(f);
or this
int a = 1;
stringstream ss;
ss << a;
string str = ss.str();
Then you can use string::substr() string::find() string::find_first_of() and similar methods to modify and format your string.
a similar topic
If you really want (have to) divide: (I think my version is cleaner & more efficient than the others)
unsigned long long userInput;
std::stringstream ss,s0;
std::string nr;
std::cout << "Enter a long long number: " << std::endl;
std::cin >> userInput;
int input=userInput;
int digits;
while(input>999){
input=input/1000;
digits=userInput-input*1000;
int mdigits=digits;
while(mdigits<100){s0<<"0";mdigits*=10;}
std::string s=ss.str();
ss.str("");
ss<<","<<s0.str()<<digits<<s;
userInput=input;
s0.str("");
}
std::string sf=ss.str();
ss.str("");
ss<<input<<sf;
std::cout << "Your Number: " << userInput << ";" << digits <<";"<<ss.str()<<std::endl;
Enter a long long number: 12345678 Your Number: 12;345;12,345,678
Here is the brute force but may be easiest to understand way to get every thousand digits with the help of a vector.
#include<iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main ( int argc, char * argv[] )
{
long long userInput;
int fthreeDigit;
cout << "Enter a long long number: " << endl;
cin >> userInput;
vector <int> res; //use vector to store every 3 digits
while (userInput !=0)
{
fthreeDigit = userInput %1000;
res.push_back(fthreeDigit);
userInput = userInput / 1000 ;
}
std::reverse(res.begin(), res.end());
for (size_t i = 0; i < res.size()-1; ++i)
{
if (res[i] ==0)
{
cout << "000"<<",";
}
else
{
cout << res[i] << ",";
}
}
if (res[res.size()-1] == 0)
{
cout << "000";
}
else{
cout << res[res.size()-1];
}
cout <<endl;
cin.get();
return 0;
}
I tested this code with the following case:
Input: 123456 Output: 123,456
Input: 12 Output: 12
Input: 12345 Output: 12,345
Input: 1234567 Output: 1,234,567
Input: 123456789 Output: 123,456,789
Input: 12345678 Output: 12,345,678
I guess this is what you want according to your response to comments.
You could do this:
#include <iostream>
#include <string>
using namespace std;
string commify(unsigned long long n)
{
string s;
int cnt = 0;
do
{
s.insert(0, 1, char('0' + n % 10));
n /= 10;
if (++cnt == 3 && n)
{
s.insert(0, 1, ',');
cnt = 0;
}
} while (n);
return s;
}
int main()
{
cout << commify(0) << endl;
cout << commify(1) << endl;
cout << commify(999) << endl;
cout << commify(1000) << endl;
cout << commify(1000000) << endl;
cout << commify(1234567890ULL) << endl;
return 0;
}
Output (ideone):
0
1
999
1,000
1,000,000
1,234,567,890
// Accepts a long number, returns a comma formatted string
CString num_with_commas(long lnumber)
{
CString num;
num.Format(%d",lnumber);
if(num.GetLength() > 3) {num.Insert(num.GetLength()-3, ',');}
if(num.GetLength() > 7) { num.Insert(num.GetLength()-7, ','); }
if (num.GetLength() > 12) { num.Insert(num.GetLength()-12, ','); }
return(num);
}