How do i change char to number? - c++

i need to change some character into numbers for example:
I = 1
R = 2
E = 3
A = 4
S = 5
G = 6
T = 7
B = 8
P = 9
O = 0
input example: HELLO IM GOOD
output example: H3LL0 1M G00D

Are you trying to make us do your homework?
Anyhow, there are multiple possibilities.
For the starter student - The most basic one is looping through your string and replacing each needed char with a new one (you can use a switch case, look-up-tables, etc).
You can convert to a string and use it's methods as such:
string s;
s="HELLO IM GOOD"
s.replace('I,'1')
s.replace('R,'2')
.
.
.
cout << s; //print solution

This code helps:)
#include <iostream>
#include<stdio.h>
using namespace std;
int main() {
string s;
getline (cin, s); //used to get string input with spaces
string s1 = "OIREASGTBP";
string s2 = "0123456789";
for (int i=0; i<s.size(); i++)
{
int a = s1.find(s[i]);
if(a != -1)
{
s[i] = s2[a];
}
}
cout<<s;
}

Related

Get all input of int from cin separated with space in c++

N = Input How much attempt (First Line).
s = Input How much value can be added (Second, fourth and sixth lines).
P = Input of numbers separated with space.
Example :
3 ( Input N )
2 ( s 1 )
2 3
3 ( s 2 )
1 2 3
1 ( s 3 )
12
Example :
Read #1: 5 (Output s1 = 2 + 3)
Read #2: 6 (Output s2 = 1+2+3)
Read #3: 12 (Output s3 = 12)
I've been searching and trying for very long but couldn't figure out such basic as how to cin based on given numbers, with spaces and add all values into a variable. For example:
#include <iostream>
using namespace std;
int main() {
int l, o[l], r, p[r], i;
cin >> l;
for(i = 0; i < l; i++) {
cin>>o[l];
r = o[l]; // for every o[0] to o[l]
}
while (cin>>o[l]) {
for (i = 0; i < l; i++){
cin>>p[o]; // for every o[0] to o[l]
// i.e o[l] = 1 then 2 values can be added (because it starts from zero)
// input 1 2
// o[1] = {1, 2}
int example += o[1];
cout<< "Read#2: " << example;
}
}
}
And it doesn't work. Then i found getline(), ignoring the s and just input anything that will finally be added to a number, turned out it is only usable for char string. I tried scanf, but I'm not sure how it works. So im wondering if it's all about s(values) × 1(column) matrix from a looping but sill not sure how to make it. Any easy solutions to this without additional libraries or something like that? Thanks in advance.
#include <iostream>
using namespace std;
int main() {
int t; //number of attempts
cin >> t;
while(t--) { // for t attempts
int n, s = 0; //number of values and initial sum
cin >> n;
while (n--) { //for n values
int k; //value to be added
cin >> k;
s += k; //add k to sum
}
cout << s << "\n"; //print the sum and a newline
}
return 0;
}
If you want to add more details, (i.e. print Read#n on the nth attempt), you can always use
for (int i = 1; i <= n; i++)
to replace while(t--) and at the end of the attempt just print
cout << "Read#" << i << ": " << s << "\n";

Insert spaces into a string

I have a string and I want to insert spaces between the digits.
Example:
Input String: 123456
Output String: 1 2 3 4 5 6
You could just call the string as an array
std::string str = "123456";
std::string new_string = "";
int string_length = 6;
for(int i=0; i<string_length; i++){
new_string += str[i];
if(i != string_length-1) { new_string += " "; }
}
There are more efficient ways to do it, but this illustrates the behavior in an easily understandable way, with little steps at a time.
With range-v3 you could do:
namespace rv = ranges::views;
auto res = s | rv::intersperse(' ') | ranges::to<std::string>;
Here's a demo.
Best way is to implement your own custom split function.
Have a look at the following implementation:
#include <iostream>
#include <string>
bool isDigit(char c){
return (c>='0' && c<='9');
}
std::string splitOnDigits(std::string s){
std::string out = "";
for(int i=0;i<s.length();i++){
if(isDigit(s[i-1]) || (!isdigit(s[i-1]) && isDigit(s[i]))){
out += " ";
}
out += s[i];
}
return out;
}
int main()
{
std::string s = "123456";
std::cout<<splitOnDigits(s)<<std::endl;
return 0;
}
Output:
1 2 3 4 5 6

How to convert a string of integer numbers into an array in c++?

The problem:
A function which gets degrees and factors as inputs and returns a equation as output.
The issue:
I did not know how to read an array of numbers in form of a string in c++ back then in 2016 when I was a super junior. I also did not know how to search good enough!
Update:
I answered my question and you can test this in this link: http://cpp.sh/42dwz
Answer details:
Main part of the code will be like this:
int main()
{
Poly mypoly("2 -4 3", "1 5 1");
return 0;
}
Inputs are 2 -4 3 and 1 5 1.
Output should be (2X) + (-4X5) + (3X)
Class Poly has a built-in feature to print the result
To make it easier we should convert degrees and factors from a single string into an array of strings.
This means that a string like 2 -4 3 changes into [2, -4, 3] which makes it easy to iterate over items and create equation sentences
This action is called splitting a string into an array by a delimiter which I found here for c++ https://stackoverflow.com/a/16030594/5864034
Rest of the code is just looping over the array of degrees and factors to create sentences(which is pretty easy just check the answer link http://cpp.sh/42dwz)
The code:
// Example program
#include <iostream>
#include <string>
#include <sstream>
#include <iterator>
using namespace std;
template <size_t N>
void splitString(string (&arr)[N], string str)
{
int n = 0;
istringstream iss(str);
for (auto it = istream_iterator<string>(iss); it != istream_iterator<string>() && n < N; ++it, ++n)
arr[n] = *it;
}
class Poly {
public:
string degree[10];
string factor[10];
Poly(string input_degree, string input_factor) {
splitString(degree, input_degree);
splitString(factor, input_factor);
for (int i = 0; i < 10; i++){
int this_degree = stoi(degree[i]);
int this_factor = stoi(factor[i]);
string this_sentence = "";
if(this_degree != 1 && this_degree != 0 ){
this_sentence = this_sentence + degree[i];
if(this_factor != 0){
if(this_factor != 1){
this_sentence = this_sentence + "X" + factor[i];
}else{
this_sentence = this_sentence + "X";
}
}
}
if(this_sentence != ""){
cout << "(" << this_sentence << ")";
}
if(stoi(degree[i+1]) != 0 && stoi(degree[i+1]) != 1){
cout << " + ";
}
}
}
};
int main()
{
Poly mypoly("2 -4 3", "1 5 1");
return 0;
}
The process of reading a string and extracting information from it into some sort of structure is called parsing. There are many ways to do this, and which way is appropriate depends on exactly what you want to do, how quickly it needs to run, how much memory you've got available and various other things.
You can write a simple loop which steps over each character and decides what to do based on some variables that store current state - so you might have a flag that says you're in the middle of a number, you see another digit so you add that digit to another variable which is collecting the digits of the current number. When the current number completes (perhaps you find a character which is a space), you can take what's in the accumulator variable and parse that into a number using the standard library.
Or you can make use of standard library features more fully. For your example, you'll find that std::istringstream can do what you want, out of the box, just by telling it to extract ints from it repeatedly until the end of the stream. I'd suggest searching for a good C++ input stream tutorial - anything that applies to reading from standard input using std::cin will be relevant, as like std::istringstream, cin is an input stream and so has the same interface.
Or you could use a full-blown parsing library such as boost::spirit - total overkill for your scenario, but if you ever need to do something like parsing a structured configuration file or an entire programming language, that kind of tool is very useful.
So for the community rules and to make it clear i want to answer my question.
#include <iostream>
#include <string>
#include <sstream>
#include <iterator>
using namespace std;
template <size_t N>
void splitString(string (&arr)[N], string str)
{
int n = 0;
istringstream iss(str);
for (auto it = istream_iterator<string>(iss); it != istream_iterator<string>() && n < N; ++it, ++n)
arr[n] = *it;
}
class Poly {
public:
string degree[10];
string factor[10];
Poly(string input_degree, string input_factor) {
splitString(degree, input_degree);
splitString(factor, input_factor);
for (int i = 0; i < 10; i++){
int this_degree = stoi(degree[i]);
int this_factor = stoi(factor[i]);
string this_sentence = "";
if(this_degree != 1 && this_degree != 0 ){
this_sentence = this_sentence + degree[i];
if(this_factor != 0){
if(this_factor != 1){
this_sentence = this_sentence + "X" + factor[i];
}else{
this_sentence = this_sentence + "X";
}
}
}
if(this_sentence != ""){
cout << "(" << this_sentence << ")";
}
if(stoi(degree[i+1]) != 0 && stoi(degree[i+1]) != 1){
cout << " + ";
}
}
}
};
int main()
{
Poly mypoly("2 1 -4", "1 3 5");
return 0;
}

How to format a string with commas like US currency? [duplicate]

This question already has answers here:
Comma Formatting for numbers in C++
(5 answers)
Closed 8 years ago.
I am trying to make a small program that takes a string and then adds commas to it in three character intervals, like how a currency amount would be formatted. (i.e. 1000 becomes 1,000 and 10000 becomes 10,000).
This is my attempt so far, and it almost works:
#include <string>
#include <iostream>
using namespace std;
int main() {
string a = "123456789ab";
int b = a.length();
string pos;
int i;
for (i = b - 3; i >= 0; i-=3) {
if (i > 0) {
pos = "," + a.substr(i,3) + pos;
}
}
cout << pos;
return 0;
}
The output with the sample string is:
,345,678,9ab
It seems it doesn't want to grab the first 1 to 3 characters. What did I do wrong with my code?
#include <string>
#include <iostream>
using namespace std;
int main() {
string a = "123456789ab";
int b = a.length();
string pos;
int i;
for (i = b - 3; i > 0; i-=3) {
if (i > 0) {
pos = "," + a.substr(i,3) + pos;
}
}
cout << a.substr(0,i+3)+pos;
return 0;
}
When the index is negative, it means that it can't make any more group of 3. But there may be 1-3 numbers which may be left. We need to explicitly add them
The first character is at index 0. But you never call substr when i is 0, so you can never get that character.

[number]-F appearing at the end of String?

I am a new to c++ and was butchering together a palindrome program at 1am on a Sunday just, because! and I have come across this problem:
Input: test
Reverse: tset3-F
Where has the 3-F come from? Sometimes it's just -F or another number-F. Where is this coming from?
Here is my code:
#include <iostream>
#include <string>
using namespace std;
int main() {
string eString;
int length;
int counter = 0;
cout << "Enter String: ";
cin >> eString;
length = eString.length();
char reverseChar[length];
for(int x = eString.length() -1; x > -1; x--) {
reverseChar[counter] = eString[x];
counter++;
}
cout << "Reverse: " << reverseChar;
}
Many thanks for your time.
You aren't adding a null terminator to the end of your strings. It's random data that happens to be in memory.
reverseChar should be length + 1 in size
The final char should be set to '\0'
reverseChar[length] = '\0';
See: http://en.wikipedia.org/wiki/Null-terminated_string
You need to add a null terminator to the reverseChar string. There is a 0 just after the last character of all strings in C, which tells string manipulation functions where the string ends in memory. The 0 is never included in the length, so you have to remember to add room for it when allocating space for a string.
char reverseChar[length + 1];
for(int x = eString.length() -1; x > -1; x--) {
reverseChar[counter] = eString[x];
counter++;
}
reverseChar[length] = 0;
I think: char reverseChar[length+1] because you need to leave space for the end of string delimiter reverseChar[length]='\0'