hi can someone please help me to complete this code in c++ if you may interested
here is the project which will print the position of a char in string, this is very close to my task but not exactly
here is the problem: program only print the position of a char, for example for letter 'S' it prints 18 because it sits at position 18, how i can change this program which instead of that, the program print my values, i don't really care about the position i care about the value that should return or store, the value i specify,
program for sam prints
S=18
A=1
M=13
instead i want it know for letter S print 7 or store 7, i mean instead of caring about position should care about the value at the final result which i explained
all 26 alphabet as you see has a value base on the position i want that pos value to be changed and result other pos int value
#include<iostream>
#include<string>
#include<exception>
#include <cstdlib>
#include<stdio.h>
#include <cctype>
using namespace std;
int main()
{
const std::string alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
cout << "Please enter your the name:";
std::string text;
std::cin >> text;
// convert all lower case characters to upper case
for (char& c : text)
c = std::toupper(c);
// Lookup character
for (char& c : text) // for each character c in text
{
const auto pos = alpha.find(c);
if (pos != std::string::npos) // if found (if the character is an alpha character)
// note: non-alpha characters are ignored
{
const int value = pos + 1; // +1 because position of 'A' is 0, value of 'A' is 1
// Print the character and the position
cout << c << "=" << pos << endl;
}
}
}
It depends on what kind of result you're looking for. If you're looking to return values in the range of the alphabet, then just rearrange the letters to match what you want them to return.
If you're looking for something with higher or lower values, then take a look at building a map and accessing the key value pairs. https://en.cppreference.com/w/cpp/container/map
Related
I'm a beginner to C++ so forgive me if I'm making a stupid mistake here.
I want to loop through a string of integers in the following code:
#include <string>
using namespace std;
int main() {
string str = "12345";
for (int i : str) {
cout << i << endl;
}
return 0;
}
But I receive the output:
49
50
51
52
53
I know that I get normal output if I use char instead of int, but why do I receive an output of integers 48 more than they should be?
When you loop through a string you get elements of type char. If you convert a char to an int you get the ASCII value of the char, which is what happens when you do:
string str = "12345";
for (int i : str) { // each char is explicitly converted to int
cout << i << endl; // prints the ascii value
}
The ASCII value of '0' is 48, and '1' is 49, etc, which explains the output you get.
Just what #cigien said, You just need to change it from int to char i.e
string str = "12345";
for (char i : str) {
cout << i << endl;
}
Or one solution for all auto keyword
string str = "12345";
for (auto i : str) {
cout << i << endl;
}
The first thing you need to know is that a string is an array/sequence of chars.
You can think of a char as a single character.
But the way it is encoded is as a number.
For example, the char 'a' is encoded (in ASCII) as the number 97.
Now your for loop says int i: str.
You're telling it to look for integers in the string.
But a string is an array/sequence of chars, not of integers.
So the loop takes each char,
and instead of looking at what the character itself is,
it gives you the integer encoding value of the char,
the ASCII value.
Now the numbers are encoded with the char '0' having the lowest encoding value,
'1' having the next value,
'2', having the next,
and so on through digit '9'.
I can never remember what the actual ASCII value for '0' is . . . .
But because the digit chars are encoded consecutively in this way,
you can convert any digit char to its int value by subtracting the underlying integer encoding value of '0'.
#include <string>
using namespace std;
int main() {
string str = "12345";
for (char c: str) {
cout << (c - '0') << endl; // gives you the actual int value, but only works if the char is actually a digit
}
return 0;
}
for (int i : str) { is infact syntactic sugar for
for (auto iterator = str.begin(); iterator != str.end(); iterator++) {
int i = (int) *iterator;
But the *-operator from string::iterator is infact an overload which returns the current char. It will as such be casted to an int. What you then see is this number. It is the integer value of the byte. Not necessarily ASCII. It could be ANSI too.
I have the code but it prints the letters in uppercase but also prints some weird characters afterwards. I just wanted to know how to just get the letters.
the program executing picture.
using namespace std;
int main()
{
const int SIZE = 81; // Constant for size of an array
const int MIN_LOWERCASE = 97; // Start of lowercase letters in ASCII
const int MAX_LOWERCASE = 122; // End of lowercase letters in ASCII
char line[SIZE]; // Initializing character line for input
cout << "Enter a string of 80 or fewer characters:\n";
cin.getline(line,SIZE); // Getting input from the user.
for (int count = 0; count < SIZE; count++)
{
if (line[count] >= MIN_LOWERCASE && line[count] <= MAX_LOWERCASE) // Checking whether the selected letter is in the reange of lowercase letters.
{
line[count] - 32;
cout << static_cast<char>(line[count] - 32); // converting and displaying lowercase letters to uppercase letters.
}
else
{
cout << static_cast<char>(line[count]);//Displaying the same character if it is in uppercase.
}
}
cout << endl;
system("pause");
return 0;
}
You need to use the actual size of the text that you read. Else you will print extra characters.
for (int count = 0; count < strlen(line); count++)
You might need #include <cstring> to use strlen().
cout << "Enter a string of 80 or fewer characters:\n";
cin.getline(line,SIZE); // Getting input from the user.
int strLen=strlen(line)
for (int count = 0; count < strLen; count++)
{
if (line[count] >= MIN_LOWERCASE && line[count] <= MAX_LOWERCASE) // Checking whether the selected letter is in the reange of lowercase letters.
{
line[count] - 32;
cout << static_cast<char>(line[count] - 32); // converting and displaying lowercase letters to uppercase letters.
}
else
{
cout << static_cast<char>(line[count]);//Displaying the same character if it is in uppercase.
}
}
Ypur loop is running 80 times no matter what is the size of string.
Actually, getline / cin / scanf etc. functions for char[] is explained following example:
The string is initialized for char c[10];. The input is "abcd".
First, c[i] is initialized unknown value, because it is local variable (If it is a global variable, you can assume that c[i] = 0)
Second, If you input, the value of c[i] only changed where 0<=i<=4 because the length of input is 4.
In this case, currently c = { 'a', 'b', 'c', 'd', '\0', ?, ?, ?, ?, ?}. (? denotes unknown value)
Third, you are looping i for 0 to size_of_array_c, so your output will be "abcd?????" (I don't know the value of ?).
So, you can fix the bug if you only loop while c[i] != '\0'.
The idiomatic way of doing this in C++ is
#include <string>
#include <locale>
#include <algorithm>
#include <iterator>
#include <iostream>
int main()
{
std::locale loc(""); //< the current system locale
std::string line; //< will contain the input line
std::cout << "Enter a string of 80 or fewer characters:\n";
std::getline(std::cin,line);
std::string lower; //< will contain the output
// This is the "key" of everything
std::transform(line.begin(),line.end(), // transform the entire input...
std::back_inserter(lower), // by writing into the back of the output string ...
[&loc](auto c){ return std::tolower(c,loc); }); // the result of std::tolower applied to all character, using the system locale
std::cout << "The transformed string is:\n" << lower << std::endl;
return 0;
}
// look ma! No pointers, array sizes, overflows and explicit memory management.
// And works consistently with the language your computer is set up.
I am trying to code a C++ program that takes a 5 character long string and then prints out the string with a new permutation with this order: 1st character, 3rd character, 5th character, 2nd character, 4th character. My code is as follows:
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
string key;
string p10;
cout << "Enter the five characters long string: ";
cin >> key;
p10 = key[0] + key[2] + key[4] + key[1] + key[3];
cout << p10 << endl;’
system(“pause”);
return 0;
}
The output (p10) is a random Greek letter every time I run it.
Please help!
The problem here is that when you use [] on a string, you're not getting back another string, but a single char. A char is actually just a small integer number (think character code), and if you use the + operator with them, it'll add the numbers together. You'll end up with a more or less random character code, which is why you get greek letters.
If you want to keep the structure of the code as close to the original as possible, you can use substr to get "one character strings" instead of plain chars:
key.substr(0, 1) + key.substr(2, 1) + ...
The 1 signifies that you want one character from the specified offset.
Another way is to first construct a char array out of the characters and then turn it into a string:
char p10_arr[] = { key[0], key[2], ... };
string p10(arr, sizeof(arr));
And perhaps the nicest and most concise way is to use the initializer list syntax:
string p10 { key[0], key[2], ... };
I need help with this if statement. Im trying to read each character to see if it is a number. If it is not a digit then say it is not a number if it is continue reading on to the next character. for example if the user inputs 54gr 21 gr42 134 3f3. the only thing that would cout is 21 and 134.
#include <iostream> // libraries
#include <iomanip>
#include <string>
using namespace std;
int main()
{
char string[80];
// char num[80];
// char good[80];
cout << "enter a string "; // prompting user
cin.getline(string,80); // geting line
// int i = 0;
// int j = 0;
int count = 0;
{
while(string[count] != '\0') {
if(string[count] >= '0' && string[count] <= '9' )
cout << count << endl;
}
++ count;
}
}
I would not try to do this character by character. The problem is that you don't now that 5 is really part of a number until you've read to the end of the string of non-space characters to verify that all the contents are legitimately part of a number.
As such, I think you need/want to break the input up into "words", then check whether each complete word can be converted entirely to a number. You can read "words" with just some_stream >> some_string;
Once you have a "word" you check whether you can convert it entirely to a number. Assuming you want integers, you use strtol to (try to) convert it to a number. That will give you a pointer to the first character it couldn't convert as a number. If that's not the end of the string, then that "word" wasn't a number (even if it started with/contained one or more digits).
I am attempting to solve a problem from topcoder.com and it's driving me crazy. I am learning C++ after a long break from C and am having trouble with strings.
The purpose of the program is to decode a string of 0s and 1s that has gone through an encryption algorithm that consists of adding each adjacent digit to the digit in question.
So 010111 becomes 112232 (LSB and MSB are considered to have zeros next to them). Below is my algorithm to decode the string:
#include <string>
#include <vector>
#include <iostream>
using namespace std;
class BinaryCode {
public:
vector<string> decode(string message);
};
vector<string> BinaryCode::decode(string message) {
vector<string> decoded(2);
int i;
string myTempString;
myTempString.append("0");
myTempString.append(1,message[0] - myTempString[0]);
for(i=2; i<message.size(); i++) {
myTempString.append(1,message[i-1] - myTempString[i-1] - myTempString[i-2]);
}
decoded[0] = myTempString;
myTempString = "";
myTempString.append("1");
myTempString.append(1,message[0] - myTempString[0]);
for(i=2; i<message.size(); i++) {
myTempString.append(1, message[i-1] - myTempString[i-1] - myTempString[i-2]);
}
decoded[1] = myTempString;
return decoded;
}
int main () {
string message("123210122");
BinaryCode *code = new BinaryCode;
vector<string> result = code->decode(message);
cout << "Decoded strings are "+result[0]+" and "+result[1];
getchar();
return 0;
}
The output is nonsense:
Decoded strings are 01
This is just a guess, since you don't show what output you're getting, but it looks like you're doing math on the character values and ending up with characters in the control range. For example, '1' - '0' is not '1' (character 49), it is 1, or Control-A. This is not printable and will typically be invisible in the output. Similarly, '1' + '2' is 49 + 50, or 99, which is 'c'. C++ is not going to magically convert these characters to integers for you. Hopefully this will give you the information you need to fix your code.
A character is an 8-bit integral type. It has the special property that, when printed, it will appear as the character that matches the ASCII value that it contains.
For example:
int valueAsInt = 65;
char valueAsChar = valueAsInt;
std::cout << valueAsChar << "\n";
valueAsInt = 'A';
std::cout << valueAsInt << "\n";
A
65
Take the value of the character literal '0'. This corresponds to the ASCII value 48. '1' is 49, etc.
If you subtract 48 from 49, you get 1. But that's not what you're looking for.
The ASCII value 1 corresponds to a non-printable character, called "start of heading". It was once used on old printers as a sort of markup. It would not print, but it would modify how further characters are printed.
When you subtract one numeric character from another, you get a delta, not a printable character. To turn this delta back into a printable character, you have to add it to a base character:
char value = '5' - '3';
value += '0';
std::cout << "5 - 3 = " << value << "\n";
5 - 3 = 2
So, your code such as message[0] - myTempString[0] must be changed to message[0] - myTempString[0] + '0' in order to work the way you intend it to.