This is what I am trying to do:
int x = 0;
char toBuffer;
while (twenty_byte_buffer[x] != '\0') // While the string isn't at the end...
{
cout << int(twenty_byte_buffer[x]); // show me, works fine
//need to concat the int values from above into toBuffer as a string
//eg. "-62-8711097109" would have derived from this "©nam"
//this doesn't work:
//strcat ( toBuffer, reinterpret_cast<*????*>(twenty_byte_buffer[x]) );
x++;
}
Any help will be greatly appreciated!
Use a stringstream. It works just like cout:
stringstream sstr;
while (twenty_byte_buffer[x] != '\0')
{
sstr << int(twenty_byte_buffer[x]);
x++;
}
string result = sstr.str();
The easiest option would be a std::stringstream:
#include <sstream>
#include <iostream>
using namespace std;
int main(){
stringstream numbers;
for(int i=0; i < 10; ++i){
numbers << i;
}
cout << numbers.str() << endl; // prints "0123456789"
}
#include<sstream>
std::stringstream sout;
while (twenty_byte_buffer[x] != '\0') // While the string isn't at the end...
{
cout << int(twenty_byte_buffer[x]); // show me, works fine
sout << int(twenty_byte_buffer[x]); //concatenating into stringstream!
x++;
}
std::string str = sout.str(); //get the string value!
cour << str ;
The right answer depends on what's really inside your twenty_byte_buffer.
If the values in twenty_byte_buffer are ASCII characters that represent integers (having the values '0' through '9', inclusive), then the stringstream solution that Daniel Gallagher posted would need to be revised slightly, removing the (int) cast:
stringstream sstr;
int x = 0;
while (twenty_byte_buffer[x] != '\0')
{
// Note no cast to int here...
sstr << twenty_byte_buffer[x];
x++;
}
string result = sstr.str();
But if the bytes in the buffer represent binary integers (having the values [-128 - 127], inclusive), then the while condition appears to be wrong: The loop will exit on the first 0 value that it encounters! (To use unsigned integers, in the range [0 - 255], change the cast to (unsigned int).)
By the way, the reason why your char toBuffer solution didn't work is twofold:
1) You need to use an array of chars, not a single char. You could declare toBuffer as char toBuffer[100], for example (and then be sure to initialize at least the first char to '\0'.)
2) The strcat would still fail if the bytes represent binary values (unsigned ints in the range [0..255], or ints in the range [-128..127]). You need a call that converts those values to their binary representation. One way of doing this uses the non-standard but commonly-supported itoa call:
char toBuffer[100];
int x = 0;
int y = 0;
// I think we still need a different terminating condition...
while (twenty_byte_buffer[x] != '\0') {
itoa(bytes[x], &toBuffer[y], 10));
y += strlen(&toBuffer[y]);
}
Related
The purpose of this code is to insert an x in between repeating letters. For example, if I were to input "CoolBoolFallmoose", the output would be "CoxolBoxolFalxlmoxose".
The code is also supposed to make an even number of pairs of letters, so if there is an odd amount of characters, an x is added to the end of the string. An example for this would be if we had "ball", it would become "balxlx" to make even pairs: "ba" "lx" "lx".
This is the code I have so far:
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main(){
string cipher, plain, paired = "";
cout << "input plaintext(no spaces, lowercase):\n";
cin >> plain;
for (int i=0;i<plain.length();i++){
if (plain[i]==plain[i+1]){
plain.insert(i,'x');
}
paired[i]=paired[i];
cout<<paired[i];
}
if (paired.length() % 2!= 0){
paired=+'x';
}
cout<<paired<<endl;
return 0;
}
The output I get is just the same as my input, no "x" added in any place.
The issue I am having is, every time I try to use the append() or insert() function for strings, I get an error from my compiler, which is xCode. Is there another way to solve this code?
EDIT: The error says:
No matching member function to call for insert
It also comes up for append().
I don't really know what you wanted to do with this part:
paired[i]=paired[i];
cout<<paired[i];
but otherwise the logic is good. Here is my take on it, x is a counter:
#include <iostream>
#include <string>
using namespace std;
int main(){
string m,n;
int x = 0;
cout << "Input: " << endl;
getline(cin, m);
for(int i = 0;i < m.length();i++){
x++;
n = n + m[i];
if(m[i] == m[i+1]){
n = n + 'x';
x++;
}
}
if((x % 2) != 0){
n = n + 'x';
}
cout << n;
return 0;
}
If you look at the available overloads of std::string::insert(), you will see that your statement plain.insert(i,'x'); does not match any of them, hence the compiler error. The overloads that takes a single char require either:
an index and a count (you are omitting the count)
an iterator and an optional count
There is, however, a couple of overloads that take just an index and a value, but they require a const char* or a std::string, not a single char.
Also, paired[i]=paired[i]; is a no-op. Except in your case, since paired has a size() of 0 since you never append anything to paired, so actually any access to paired[...] is undefined behavior.
Try this instead:
#include <iostream>
#include <string>
using namespace std;
int main(){
string plain, paired;
cout << "input plaintext(no spaces, lowercase):\n";
cin >> plain;
paired = plain;
for (string::size_type i = 1; i < paired.size(); ++i){
if (paired[i] == paired[i-1]){
paired.insert(i, 1, 'x');
// or: paired.insert(paired.begin()+i, 'x');
// or: paired.insert(i, "x");
// or: paired.insert(i, string{'x'});
// or: paired.insert(paired.begin()+i, {'x'});
++i; // skip the x just inserted
}
}
if (paired.size() % 2 != 0){
paired += 'x';
}
cout << paired << endl;
return 0;
}
Demo
A couple of points
First, Although the string.insert function says it takes an int as its first argument it really wants an iterator in this case.
Second, you are inserting elements into your "plain" string which increases its length and you have plain.length within your loop so you create an infinite loop.
Third, insert inserts BEFORE the index so you need to add 1 to I.
The code below will work for your loop:
Int len = plain.length();
Int count = 0;
for (int i = 0; i < len + count; i++)
{
If (plain[i] == plain[i + 1])
{
plain.insert(plain.begin() + (i +1), 'X');
++count;
}
}
cout << plain;
And as, mentioned below, if you want to handle spaces you can use getline(cin, plain) instead of cin.
As part of my homework assignment, I have to split a char[] by its indices. So for example, the main function looks like:
int main()
{
char str[] = "A string to be split into given number of parts";
int split_size;
cout << "Enter the size of the part: ";
cin >> split_size;
int size = sizeof(str) / sizeof(str[0]);
SplitString(str, split_size, size);
int wait;
cin >> wait;
return 0;
}
Then using the function SplitString, the first x elements are printed, new line, then the next.
My first idea, was to use two for loops. One loops through the splits (i.e. if there are 4 splits, the range on this loop is 0 to 3), then the second loops through the split itself, iterating over the array elements.
My SplitString() function looks like this:
void SplitString(char str[], int split_size, int size) {
int parts = size / split_size;
for (int i = 0; i < parts; i++) {
for (int j = 0; j < split_size; j++) {
j = split_size * i;
cout << str[j];
}
cout << endl;
}
}
Is there an easier way to do this? I know in Python, you can use the arr[1:] to grab a range of elements from the array. Is there anything similar in C++? Is there some flaw in my logic? Is there something wrong with my code?
cout comes with a write function that takes a pointer and a size argument.
for (int i = 0; i < parts; i++) {
cout.write (str+i*split_size, split_size)
cout << endl;
}
Note that the code above does not check if the string is actually long enough. If the total size is not equal the split_size times a whole number, you will have to add an additional check.
Also, note that this:
int size = sizeof(str) / sizeof(str[0]);
can be written as:
int size = sizeof(str);
instead because the size of a char is always 1.
You can use std::string for this. Alternatively, if your compiler supports C++17, you can use std::string_view as the first argument of SplitString to avoid unnecessary copying.
#include <algorithm>
#include <iostream>
#include <string>
void SplitString(std::string s, std::size_t split_size)
{
while(!s.empty())
{
auto size = std::min(split_size, s.size());
std::cout << s.substr(0, size) << '\n';
s = s.substr(size, std::string::npos);
}
}
int main()
{
char str[] = "A string to be split into given number of parts";
int split_size = 5;
SplitString(str, split_size);
return 0;
}
Live example.
char binarycode[5][5];
string tmp;
cout<<"Please type first 5 binary numbers: ";
cin>>tmp;
char tmp2[5];
strcpy(tmp2, tmp.c_str());
binarycode[0] = tmp2;
This is my code for me to save the empty char array with user input string. So there will be 5 string that will break up to one dimension char array and will be saved to each row of binarycode. Howerver, it does not seems to work like Java where i can just store the one dimension array to two dimension array. Are there any way to make this process easier or is making method is better?
Are there any way to make this process easier or is making method is
better?
Consider using std::vector of std::string like std::vector < std::string > binarycode ;
Then,
binarycode.reserve( 5 );
std::string tmp;
for ( int i = 1; i <=5; ++i )
{
std::cin >> tmp;
binarycode.push_back ( tmp );
}
Your objective is to take a 1 dimensional array with size T and to populate or convert it to a 2 dimensional array with size MxN. What you will need to do in order to construct this algorithm before writing any code implementation is you will need to know before hand the sizes or lengths of both M and N and in your case you have explicitly expressed that it will be a 5x5 in size; T shouldn't matter in this case. M will be the size of your rows, where N will be the size of your columns. To do this you will need to traverse the single array for its size and then depending on its indexed value it should correspond to a (m,n) value. Another words you need to map A(n) to B(m,n).
The method that you are trying to achieve which is not the simplest or even the most efficient but mimics the algorithm mathematically would be as follows:
#include <iostream>
#include <string>
int main() {
char binaryCode[5][5] { 0 }; // Initialize to all 0s
char temp;
int row = 0;
int col = 0;
do {
std::cout << "Enter 5 binary number: ";
std::cin >> temp;
for ( ; col < 5; col++ ) {
binaryCode[row][col] = temp[col];
}
col = 0;
temp.clear();
row++;
} while( row < 5 );
row = 0;
col = 0;
std::cout << "\nResults:\n";
for ( ; row < 5; row++ ) {
for ( ; col < 5; col++ ) {
std::cout << binaryCode[row][col] << " ";
}
std::cout << "\n";
col = 0;
}
return 0;
}
However this first approach is a little naïve and as P0W already stated with his answer:
#include <iostream>
#include <string>
#include <vector>
int main() {
std::vector<std::string> binaryCodes;
binaryCodes.reserve( 5 );
std::string tmp;
for ( int i = 1; i <=5; ++i ) {
std::cin >> tmp;
binarycode.push_back ( tmp );
}
return 0;
}
Is cleaner and simpler and does exactly the same thing that you would need.
The strcpy(0 function copies entire c-string to memory position you designated as destination. In code
char tmp2[5];
strcpy(tmp2, tmp.c_str());
In code
binarycode[0] = tmp2;
you attempted to save pointer - address of that buffer to a byte.
you statically allocated 5 bytes(!) of memory, then attempted to copy string to that memory. If anything, you would cause memory corruption this way, because rest of string would go somewhere.
C++ is not Java and you should thoroughly read books on this language, about syntax and standard you're using, not relying on something that "looks like". There are even principal differences between C and C++ in some areas.
If anything, iostreams provide all tools you need to get values from user input, but "proper" way to do requires handling cases of incorrect input. Consider this function:
#include <limits>
#include <iostream>
char getChar()
{
while (1) // Loop until user enters a valid input
{
std::cout << "Enter a byte value: ";
int x; // if we'll use char, cin would assume it is a character
std::cin >> x;
if (std::cin.fail()) // has a previous extraction failed?
{
// let's handle the failure
// or next >> will try parse same input
std::cout << "Invalid input from user.\n";
std::cin.clear(); // put us back in 'normal' operation mode
std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
// and remove the bad input
}
//else if ( ((char)(x & 0xff)) != x ){
else if(( x > std::numeric_limits<char>::max()) ||
( x < std::numeric_limits<char>::min()))
{
// char can be from -127 to 127, it's one byte..
// int is allowing large values
std::cout << "Invalid value.\n";
}
else // nope, so return our good x
return (char)(x & 0xff);
}
}
The char is a pain in the backside with std::iostream, it always should be an int instead. Casting to smaller variable, like (char)x might be an undefined behavior, so need to mask larger values (char)(x & 0xff); For other types this function can become a template based on the type requested.
Now we should make it understand binary input? there is no predefined manipulator for binary format, you must input a string, validate it, and convert yourself.
int binaryToDec(std::string number)
{
int result = 0, pow = 1;
for ( int i = number.length() - 1; i >= 0; --i, pow <<= 1 )
result += (number[i] - '0') * pow;
return result;
}
std::string validateEntry()
{
bool valid = true;
std::string tempStr;
do
{
valid = true;
getline(std::cin, tempStr);
for (int i = 0; i < tempStr.length(); i++)
{
if ((tempStr.compare(i, 1, "0") != 0) && (tempStr.compare(i, 1, "1") != 0))
{
valid = false;
std::cout << "Enter Valid Binary Number: ";
break;
}
}
} while (valid == false);
return tempStr;
}
Use those in pattern:
std::cout << "Enter Binary Number: ";
std::string binaryString = validateEntry();
int binaryNum = binaryToDec(binaryString);
For my class, I am to write a program in C++ that converts each character in a sentence to the opposite case (upper to lower, lower to upper). We are supposed to use arrays and a user-defined method, and this is what I came up with:
#include <iostream>
using namespace std;
// declare variables
int count = 0; // array counter
int i = 0; // loop control
char ch[100]; // each character entered will be stored in this array
char newCh[100]; // this will hold each character after its case has been changed
main()
{
cout << "Enter a sentence." << endl; // prompts user
while ( ch[count] != '\n' ) // loop continues until "enter" is pressed
{
cin >> ch[count]; // store each character in an array
count += 1; // increment counter
}
int convert(); // call user-defined function
}
// even though it isn't necessary, we are using a user-defined function to perform the conversion
int convert()
{
for ( i = 0; i >= 0; i++ )
{
if ( (ch[i] > 64) and (ch[i] < 91)
)
{
newCh[i] = tolower(ch[i]);
}
else
{
newCh[i] = toupper(ch[i]);
}
cout << newCh[i];
}
}
I'm not sure why, but it doesn't work. I don't believe that my while loop is terminating and executing the rest of the program. Any advice would be greatly appreciated.
The loop condition in while ( ch[count] != '\n' ) is wrong, as all entries in ch will be initialized to zero by the compiler, and as you increase count inside the loop the condition will never be false and you have an infinite loop, causing you to write beyond the limits of the array.
And writing beyond the limits of an array leads to undefined behavior, and will cause your whole program to be illegal.
I suggest you learn about std::string and std::getline.
There's a problem with your for loop - you want for ( i = 0; i < count; i++ ). Also your function can be void and you need to pass the count value into it (and you just need to invoke it with convert() without int or void in front.
I have rewrite your code with some modification. The following code works perfectly in my machine -
#include <iostream>
#include<cstdio>
#include<string>
using namespace std;
void convert(char *, int);
string line;
char input[1024];
char output[1024];
main()
{
cout << "Enter a sentence." << endl;
while (getline(cin, line)) { // POINT 1
cout<< line<<endl;
//converting to char array since you need char array
//POINT 2
for(int i=0; i< line.length(); i++){
input[i]=line[i];
}
convert(input, line.length());
cout<<output<<endl;
input[1024] = {0}; //POINT 3
output[1024] = {0};
}
}
//Custom Convert Method
void convert(char input[], int size){
for(int i = 0; i < size; i++){
if(input[i] >= 'a' && input[i] <= 'z'){
output[i] = toupper(input[i]);
} else {
output[i] = tolower(input[i]);
}
}
}
Note some points (in my comment) here -
POINT 1: reading a n entire line using getline() method. Here line is a string
POINT 2: since you need char array here I am converting the string line to char array input[1024]
POINT 3: input and output array are being reset to work with the next value;
Output of the code:
"Ctrl+C" will terminate the program
Hope it will help you.
Thanks a lot.
Okay so I'm working a calculator program that takes in a user input(ex. "(3+(4+12))"), and I need to parse the user's input and store it in an array of strings but I am having trouble doing so. My code currently is this
void parseInput(string input) {
vector <string> input_vector;
for(int i = 0; i < input.size(); ++i) {
if(isdigit(input.at(i)) == 0 && isdigit(input.at(i + 1)) == 0) {
++i;
input_vector.push_back((input.at(i) + input.at(i+1)));
}
else {
input_vector.push_back(input.at(i));
}
}
for(int i = 0; i < input_vector.size(); ++i) {
cout << endl << input_vector[i];
}
}
I know my problem is coming from trying to add a char to an vector of strings, but how would I get each char in the string and keep it as a string to store into my vector. Or is there a better way to parse this out??
edit
Okay so what I am having the most trouble with is the problems that come from the 12 splitting up into two separate chars "1 * 2" How would I go about so that it represents 12 and doesn't split it up???
Here is a solution (using c++11):
#include <algorithm>
#include <string>
#include <vector>
#include <iostream>
int main() {
std::string const input = "(3+(4+12))";
std::vector<std::string> chars(input.length());
// Maps each character of `input` to `std::string`
// with that character and saves the results in
// corresponding position in `chars` vector:
std::transform(input.cbegin(), input.cend(), chars.begin(),
[](char c) {
// One of the ways to cast `char` to `std::string`:
return std::string(1, c);
});
// To be sure it works properly, it prints
// generated strings:
for (size_t i = 0; i < chars.size(); ++i) {
std::cout << chars[i];
}
std::cout << std::endl;
}
The answer is u need to split the string into tokens, i have given an example which will add 4 to 12, to make it 16, but think that the string does'nt have any brackets, suppose if the user entered 4+12 and u need to add it you can do the following:
char string[10], nstr[10];
int p=0, a=0, b=0, op=0;
cin>>string; // input string
While (string[i]!='+' || string[i]!='-')
{
nstr[p]=string[i]; // copy the contents of string to nstr.
p++;
i++;
}// loop exits if the string[i] reaches to the operator (+/-*).
nstr[p]='\0';
a=atoi(nstr);// convert the string to integer.
op=i;// this will hold the position of array of the operator in the string.
i++;
p=0;
while (string[i]!='\0')
{
nstr[p]=string[i];// this will copy the contents of the string after the operator.
i++;
p++;
}
nstr[p]='\0';
b=atoi(nstr);
if (string[op]=='+')// check what the user want to do. Add/subtract/divide etc.
c=a+b;
else if (string[op]=='-')
c=a-b;
This program is not tested but will work, if not then use the logic in your program, like i did in my program, this will not take 1 and 2 sepratly, instead it will take 4 and 12, you can type more charaters but is limited to long, i used int here to get the return value of atoi(), hope this helps u...