I got stuck in this problem.
I'm writing a c++ program in which:
1- you write a 6 chars string
2- that string is converted into bits (let's call this 'A')
3- this string of bits is copied in another string and reverted via reverse() method (let's call this 'B')
4- a bitwise OR is executed between A and B (let's call this result 'C')
5- (here's where i got stuck) C should be converted into ASCII.... but i'ts not. I get in output strange symbols/question marks.
Here's the code:
#include <iostream>
#include <bitset>
#include <sstream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
// PART ONE: from string to bits
string input;
cout << "Insert the 6 letters string you want to convert: \n";
do
{
getline(cin, input);
if (input.length() < 6 || input.length() > 6)
{
cout << "\nIt must be 6 letters!\n";
}
} while (input.length() != 6);
string inbits;
bitset<8> newbits;
for (size_t i = 0; i < input.size(); ++i)
{
newbits = bitset<8>(input.c_str()[i]);
string aux = newbits.to_string<char, std::string::traits_type, std::string::allocator_type>();
inbits.append(aux);
}
cout << endl << inbits << endl;
// PART TWO: bitwise or
string inverted = inbits;
reverse(inverted.begin(), inverted.end());
bitset<48> bstr1(inbits), bstr2(inverted), finale;
finale = bstr1 | bstr2; // here it is done the bitwise OR
cout << finale << endl;
string ored = finale.to_string<char, std::string::traits_type, std::string::allocator_type>();
// PART THREE: from bits to string of char
stringstream sstream(ored);
string aux = "";
while (sstream.good())
{
bitset<8> bits;
sstream >> bits;
char c = char(bits.to_ulong());
aux += c;
}
cout << "the ored string is: " << aux << endl;
}
I don't know what goes wrong. I mean, it could be a sort of """overflow""" but
it just doesn't make any sense.
How should i proceed?
(Sorry for my bad english, this is the first time I open a thread here, I'm kind of unsure on how to move here)
If your results dont fall into the range 0x41 to 0x5A you wont get a alphabetical result:
Link to the ascii table site
Related
I want to ask 6 digit pins from user, I tried this code, it does work. The problem is that it cannot read pin starting from 0. The objective of the code is to read 6 digit pin no matter what the start is, as long as it is an integer it will read the correct output.
using namespace std;
int main(){
int pin[0];
cin>>pin[0];
if (pin[0] >= 100000 && pin[0] <= 999999) {
cout << pin[0];
}
else {
cout << "Invalid input!";
}
}```
On the one hand you want to read an integer (you are comparing it to 100000 and 999999) on the other hand you want to read individual digits into an array. It cannot be both. And you cannot have an array of size 0.
Just stay with the single integer. If you want to access individual digits you can convert it to a string and access characters (you already made sure that it has 6 digits):
#include <iostream>
#include <string>
int main(){
int pin;
std::cin>>pin;
if (pin >= 100000 && pin <= 999999) {
std::cout << pin << "\n";
std::string pin_string = std::to_string(pin);
for (size_t i=0; i<6; ++i){
std::cout << pin_string[i] << "\n";
}
}
else {
std::cout << "Invalid input!";
}
}
Heres one way to do it.
Read CIN as std::string
Regex recv string for digit only
Confirm recv string len is == 6
Do w/e you want with it from there
Another way could be getChar()
Why is there an extra character at the end of my string?
#include <iostream>
using namespace std;
int main() {
int num;
cin >> num; // Reading input from STDIN
cout << "Input number is " << num << endl; // Writing output to STDOUT
char c1, s2[10];
for (int i=0; i<num; i++)
{
cin >> c1;
if(c1==0){
break;
}
s2[i] = c1;
}
cout <<"output= "<< s2;
}
output example
4
Input number is 4
a l e x
output= alex#
Why is the "#" being added to the end of the string? At first i thought it was a random garbage value but every time I run the program its always the same symbol
cout, when printing a c-string, expects it to zero terminated. Whereas you haven't done so for the array s2.
You can zero initialize the entire array:
char s2[10] = {};
Or just zero terminate the last byte:
int i = 0;
for (i=0; i<num; i++)
{
cin >> c1;
if(c1==0) {
break;
}
s2[i] = c1;
}
s2[i] = '\0';
In any case, you need to be wary of potential buffer overflow (e.g. if num is too large).
Alternatively, you can consider using std::string instead of a fixed length array.
You're reading from a memory location that hasn't been initialized. By using an array of ten characters and only initializing the first four (or whatever else the number is), all other characters stay uninitalized. What data is actually read from an uninitialized location is undefined, meaning it's pretty much up to your compiler that chooses to read the equivalent value of "#" from that location. You can fix that issue by using a memory bit of the appropriate size. For this, you just replace the line
char c1, s2[10];
with
char c1;
char* c2 = new char[num + 1] //num + 1 is necessary to contain a string terminator, see the other answers
this way, you dynamically allocate exactly the size you need.
Don't forget to delete[] c2; afterwards.
You are using a Character sequence well explained here.
By convention, the end of strings represented in character sequences
is signaled by a special character: the null character, whose literal
value can be written as '\0' (backslash, zero).
In this case, the array of 20 elements of type char called foo can be
represented storing the character sequences "Hello" and "Merry Christmas" as:
Notice how after the content of the string itself, a null character
('\0') has been added in order to indicate the end of the sequence.
The panels in gray color represent char elements with undetermined
values.
I offer a c++17 solution with the constructor initialization although I may prefer either a dynamic array or std::string instead of a char.
I also added a simple integer check that always should be used.
Also a few versions of avoiding the use of the whole namespace std for various reasons, mostly to avoid unnecessary errors.
#include <iostream>
#include <limits> //numeric_limits
using std::cout, std::endl, std::cin; //<- explicit declared
int main() {
int num;
while(!(cin >> num)){ //check the Input format for integer the right way
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
cout << "Invalid input. Try again: ";
};
cout << "Input number is " << num << endl;
char c1, s2[num+1]{}; // Initialize with an empty string
for (int i = 0; i < num; i++)
{
cin >> c1;
if (c1 == 0) {
break;
}
s2[i] = c1;
}
cout << "output= " << s2 << endl;
return 0;
}
This happens because s2 is actually not a string and does not have the \0 character, which would mean the end of the string. Therefore, cout prints your string and will continue to move further in memory, byte by byte, interpreting each of them as a character to be output until it encounters the \0 character. In order to fix this, you can initialize s2 with an empty string, so the array will initially be completely filled \0.
#include <iostream>
using namespace std;
int main() {
int num;
cin >> num;
cout << "Input number is " << num << endl;
char c1, s2[10] = ""; // Initialize with an empty string
for (int i = 0; i < num; i++)
{
cin >> c1;
if (c1 == 0) {
break;
}
s2[i] = c1;
}
cout << "output= " << s2;
}
My goal is to make a program that inputs a phone number and outputs it in a standard format. It skips over any non-number characters, will output if there are not enough digits, and will also skip over any digits after the first ten digits. My raptor worked without a hitch, but it's been difficult to translate it to C++.
I am using Microsoft Visual Studio.
The problem is it is not running. If I put in anything more then one number in, I receive a fail error.
I am having some difficulty running this code.
Any and all help and advice would be greatly appreciated.
#include <iostream>
#include <string>
using namespace std;
void format(char outArray[], string inNumber)
{
outArray[0] = '(';
outArray[4] = ')';
outArray[5] = ' ';
outArray[9] = '-';
outArray[1] = inNumber[0];
outArray[2] = inNumber[1];
outArray[3] = inNumber[2];
outArray[6] = inNumber[3];
outArray[7] = inNumber[4];
outArray[8] = inNumber[5];
outArray[10] = inNumber[6];
outArray[11] = inNumber[7];
outArray[12] = inNumber[8];
outArray[13] = inNumber[9];
}
int main()
{
string phone, inNumber;
cout << "Please enter a phone number: ";
cin >> phone;
int index = 0;
int num = 0;
char outArray[14];
for (index; phone[index] >= '0' && phone[index] <= '9'; index++)
{
inNumber[num] = phone[index];
num++;
}
if (inNumber.size() > 10)
{
format(outArray, inNumber);
cout << "The properly formatted number is: ";
cout << outArray;
}
else {
cout << "Input must contain at least 10 digits." << endl;
}
system("pause");
return 0;
}
A few things to note:
Use std::string instead array of char array.
You do not need to check charters using a for loop unless you are not sure about the input(phone). However, if that's the case, use std::getline() to get the input and parse as follows using a range-based for loop.
You can use std::isdigit to check the character is a digit.
My goal is to make a program that inputs a phone number and outputs it
in a standard format. It skips over any non-number characters, will
output if there are not enough digits, and will also skip over any
digits after the first ten digits.
That means the number should have a minimum length of 10. Then the
if statement should be if (inNumber.size() >= 10)
Need a pass by ref call in the function format(), since you want to change the content of outArray. Additionally, inNumber could be a
const ref, since we do not change this string.
Updated code: (See a sample code online)
#include <iostream>
#include <string>
#include <cstddef> // std::isdigit, std::size_t
void format(std::string& outArray, const std::string& inNumber) /* noexcept */
{
for (std::size_t index = 0; index < 10; ++index)
{
if (index == 0) outArray += '(';
else if (index == 3) outArray += ") ";
else if (index == 6) outArray += '-';
outArray += inNumber[index];
}
}
int main()
{
std::string phone;
std::cout << "Please enter a phone number: ";
std::getline(std::cin, phone);
std::string inNumber;
for (char letter : phone)
if (std::isdigit(static_cast<unsigned char>(letter))) // check the letter == digits
inNumber += letter;
if (inNumber.size() >= 10)
{
std::string outArray;
format(outArray, inNumber);
std::cout << "The properly formatted number is: ";
std::cout << outArray;
}
else {
std::cout << "Input must contain at least 10 digits." << std::endl;
}
return 0;
}
inNumber[num] = phone[index]; //undefined behavior.
You cannot subscript inNumber now, since its capacity is 0, thus it can not store or access any element here.
You may need to use string's constructor whose parameter has a size_t type or string::reserve or string::resize.
And I'm happy to see cppreference get more complete now, learn to use it: http://en.cppreference.com/w/cpp/string/basic_string
BTW, this function won't do anything you want to:
void format(char outArray[], string inNumber)
maybe you'd like to have an signature like this?
void format(char outArray[], string& inNumber)
well I'm trying to get the user to input an integers as much as they want, until they input a negative number. 1st step was to use the ATOF function to convert string to number(which I did), and then allow the user to input integers(I only manage to do once just to see if I can use the atof function correctly.
Any help/tips is appreciated on giving me the right direction.
Here is my code thus far:
#include <iostream>
#include <string>
int main() {
using namespace std;
char buffer[256];
char tempBuff[256] = {'\n'};
double result;
int count = 0;
cout << "Testing " << endl;
cout << "Enter Any integers: ";
cin.getline(buffer,256);
for(int i = 0; i < strlen(buffer); i++)
{
if(isdigit(buffer[i]))
{
tempBuff[count] = buffer[i];
count++;
}
}
if (atof(tempBuff) > 0) {
result = atof(tempBuff) / 2;
}
cout << endl << "The integer you put was: " << tempBuff
<< " And dividing the integers "<< result << endl;
cin.ignore();
return 0;
}
How is atof supposed to know how many valid digits tempBuff contains? The atof function only accepts a C-style string as its input. Otherwise, it has no way to know how many characters are valid.
You can use tempBuff[count] = 0; before the call of atof. A C-style string is terminated by a zero byte.
First post! This is my second semester with "Advanced C & C++" so any help is GREATLY appreciated. I've already scoured as much of stackoverflow and a few other resources to try and help me understand what I'm doing (or not doing) with this slew of logically inept code.
The goal of this program is to recognize whether or not a 'number' given by the user is a palindrome. Sounds simple enough right?! Ugh...well this is what I have been stuck on:
#include <iostream>
using std::cout;
using std::cin;
#include <string>
using std::string;
#include <cstdlib>
int main()
{
//variable declarations
string buffer;
//user input
cout << "Enter a number to see if it is a palindrome[Q to quit]: ";
getline(cin, buffer);
//looooop
while(buffer != "Q" && buffer !="q")
{
int userNum, length, sum = 0, temp;
userNum = atoi(buffer.c_str());
for(temp = userNum; userNum !=0; userNum=userNum/10)
{
length = userNum % 10;
sum = sum*10+length;
}
if(temp==sum)
cout << temp << " is a palindrome!!\n\n";
else
cout << buffer << " is NOT a palindrome!\n\n";
cout << "Enter a number to see if it is a palindrome[Q to quit]: ";
getline(cin, buffer);
}
}
The problem arises when input of "010", or "400" is given. "400" is essentially "00400" in this case and both should be seen as a palindrome.
A better approach would be to get trailing zeros for the given number as below:
int noOfTrailingZeros = str.length;
while(str[--noOfTrailingZeros]=='0');
noOfTrailingZeros = str.length - noOfTrailingZeros;
Or the integer way as:
int noOfTrailingZeros = str.length;
while(num%10==0)
{
noOfTrailingZeros++;
num/=10;
}
Now, check for the input string whether it has the same number of zeros befire the number or not as:
int counterZeros = 0;
while(str[counterZeros++]=='0');
check these 2 numbers and if trailing zeros are more than the zeros at beginning, add that many at the beginning and pass that string to palindrome function.
First of all, to recognize a palindrome, you don't have to do atoi. Just pass from the start to the middle checking if
buffer[i] == buffer[length - i]
Second, use the atoi to make sure it is a number and you're done.
Other way is to compare the string with itself reversed:
string input;
cout << "Please enter a string: ";
cin >> input;
if (input == string(input.rbegin(), input.rend())) {
cout << input << " is a palindrome";
}