I have no idea how to cast str[str.size()-2] and str[str.size()-1] as integers. I need to return answers as integers.
int main()
{
cin>>D;
int k;
int z;
int*tab=new int [D];
for (int i=0;i<D;i++)
{
cin>>tab[i];
}
for (int i=0;i<D;i++)
{
z=silnia(tab[i]);
string str = to_string(z);
if (str.size()>1)
cout<<str[str.size()-2]<<" "<<str[str.size()-1];
else
cout<<"0 "<<str[0];
cout<<endl;
suma=1;
}
return 0;
}
I think you can use substr and atoi.
string std::string::substr (size_t pos = 0, size_t len = npos) const;
Generate substring
Returns a newly constructed string object with its value initialized to a copy of a substring of this object. The substring is the portion of the object that starts at character position pos and spans len characters (or until the end of the string, whichever comes first).
http://www.cplusplus.com/reference/string/string/substr/
int atoi (const char * str);
Convert string to integer
Parses the C-string str interpreting its content as an integral number, which is returned as a value of type int.
http://www.cplusplus.com/reference/cstdlib/atoi/
you can include sstream library then simply do the following:
stringstream a(str[str.size()-2]);
int x;
a >> x;
now x has the value of whatever ur string was and you can freely return x
Related
I have to use a function that takes two strings and one integer value that tell the position at which the second string is to be entered in the first.
For Example:
String 1 = "I have apple"
String 2 = "an "
position = 6,
Output:
String 1 = "I have an apple"
Here's my code, so far:
#include <iostream>
using namespace std;
const int SIZE=102;
void insertString(char str1[ ],char str2[ ],int position);
int main()
{
char str1[SIZE], str2[SIZE];
int position,i=0,j=0;
cout<<"Enter string 1 of atmost 50 characters:\n";
cin.getline(str1,SIZE/2);
cout<<"Enter string 2 of atmost 50 characters:\n";
cin.getline(str2,SIZE/2);
cout<<"Enter Position number where String 2 is to be inserted: ";
cin>>position;
while(position<0||position>50)
{
cout<<"Invalid input. Enter a positive Position number less than 51\n"<<
"where String 2 is to be inserted: ";
cin>>position;
}
insertString(str1,str2,position);
cout<<"Modified string 1: "<<str1<<endl;
system("pause");
return 0;
}
/******************************************************************************
Definition of function insertString:
This function takes two C-string in form of character arrays and one integer value
as parameters
It inserts String 2 in String 1 on the required position.
*******************************************************************************/
void insertString(char str1[ ],char str2[ ],int position)
{
char temp[SIZE];
int i,j,countStr2;
for(j=0;j<SIZE&&str2[j]!=0;j++)
countStr2=j;
for(i=position,j=0;i<SIZE,j<=countStr2; i++,j++)
{
temp[i]=str1[i];
str1[i]=str2[j];
}
}
This logic overwrites some characters of string 1. What should I do?
Any help will be appreciated.
#include<cstring>
#include <iostream>
/*The following function supposes that str1 and str2 are cString (i.e)
ended by `\0` and inserts str2 in str1 at the specified position in a
newStr, then returns the new string as apointer*/
char* insertString(const char str1[ ],const char str2[ ],const int& position)
{
int shiftedPos=position-1;
int str2Size=strlen(str2);
int str1Size=strlen(str1);
int newSize=str2Size+str1Size+1;
char* newStr=new char[newSize];
for(int i=0; i<shiftedPos; i++) newStr[i]=str1[i];
for(int i=0; i<str2Size; i++) newStr[shiftedPos+i]=str2[i];
for(int i=0; i<newSize; i++) newStr[shiftedPos+str2Size+i]=str1[shiftedPos+i];
newStr[newSize]='\0';
return newStr;
}
int main(){
auto str1 = "I have apple";
auto str2 = "an ";
std::cout<<insertString(str1,str2, 8);
return 0;
}
Another code to perform exactly as you wanted
#include<iostream>
#include<cstring>
/*The following function supposes that str1 and str2 are cString (i.e)
ended by `\0` and that the memory allocated by str1 >= the len(str1)+len(str2)+1.
It inserts str2 in str1 at the specified position in str1*/
void insertString(char str1[ ], char str2[ ], int position)
{
int str1Size=strlen(str1);
int str2Size=strlen(str2);
int newSize=str2Size+str1Size+1;
int cppPosition=position-1;
for(int i=str1Size; i>=cppPosition; i--) str1[i+str2Size]=str1[i];
for(int i=0; i<str2Size; i++) str1[cppPosition+i]=str2[i];
str1[newSize]='\0';
}
int main(){
char str1[50]= "I have apple";
char str2[50] = "an ";
insertString(str1,str2, 8);
std::cout<<str1;
return 0;
}
If you have to implement the void insertString(char str1[ ],char str2[ ],int position) function, you don't have many options here.
One of the possible solutions is to shift the characters in the first string to the right to make space for the second string to be inserted there.
Such an approach might look like this:
void insertString(char str1[], char str2[], int position) {
const int len1 = strlen(str1);
const int len2 = strlen(str2);
// First, shift all the characters from the given position to the right by `len2` positions:
for (int i = 0; i < len1 - position; ++i) {
str1[len1 - i - 1 + len2] = str1[len1 - i - 1];
}
// Then insert the second string in the given position:
for (int i = 0; i < len2; ++i) {
str1[position + i] = str2[i];
}
// Make sure to create a new terminator since the
// previous one got overwritten by the the first loop
str1[len1 + len2 + 1] = 0;
}
LIVE DEMO
Note, that this is potentially insecure! If there is not enough space in the str1 array to store another strlen(str2) characters, it will lead to a buffer overflow.
Way more secure option would be to allocate a new buffer for your new concatenated string on the heap, but for the sake of your assignment, this should suffice.
Since you're using C++, you should avoid this approach altogether in any production code, replacing char arrays with std::string, for example. But I've already read in the comments that you can't use it just yet.
Assuming you can use <string>, then I would put std::string::substr to use:
#include <string>
std::string originalString = "I have apple"; // original string
std::string insert = " an "; // added space beforehand for the new word to be inserted
int position = 6; // index where the new word would be inserted
int remainingStringSize = originalString.length() - position - 1; // count how many characters remain from the position you're inserting
std::string combinedString = originalString.substr(0, 6) + insert + originalString.substr(position +1, remainingStringSize); // resulting combined string
Words of caution, you obviously would need to check the following:
That index position is within the length of the original string where you wish to insert
That the remaining # of characters is more than 0
Someone will help me, in understanding the while loop in following code about what it does? for example, take input from the user: 1 2 3 8 (input size not given) and one value (any index) show size of an array. it is printing the maximum value of the array. here the answer is 8.
#include<bits/stdc++.h>
#define ll long long
using namespace std;
int main()
{
int t;
cin >> t;
while(t--)
{
string x;
getline(cin, x);
ll p;
istringstream iss(x);// use of this function
vector<ll> v;
ll ans;
while(iss>>p)// what this loop do
{
v.push_back(p);
}
ll size=v.size()-1;
sort(v.begin(), v.end());
if(size==v[size])
{
ans=v[size-1];
}
else
{
ans=v[size];
}
cout<<ans<<"\n";
}
return 0;
}
istringstream iss(x) creates a string stream called iss consisting of the string x. iss >> p extracts the next element from the iss stream and puts it into p. the return value is int because the variable p is of type int.
while(iss>>p) // get an int value from string stream iss
{
v.push_back(p); // push the int value to the vector
}
you have to use cin.ignore() after cin. otherwise the next getline function will take only new line character. like this:
cin >> t;
cin.ignore();
string str;
cin>>str;
int size = str.size(),arr[size]; //array of size equal to string size
for(int i=0;i<size;i++)
{
arr[i] = (int)str[i]-'0'; //typecasting to int
}
for str[i]-'0' the explanation is :
What is the purpose of using str[i]-'0' where str is a string?
Error may occur if unable to typecast
Using function stoi() (for int values) or stol()(for long values) also optionfor integer values.
int n=56; // use #include<bits/stdc++.h>
string s=to_string(n); // we get string "56" that's for integer to string
int x=stoi(substr(index,length));// for string to integer
So i'm trying to produce the sum of the variable date of type char in the following code using the atoi() function. But when doing so it returns this error message: test.cpp:9:25: error: invalid conversion from ‘char’ to ‘const char*’ [-fpermissive] and i can't seem to figure out what the problem is, help would be greatly appriciated.
#include <iostream>
using namespace std;
int calcNumber(const char* date, const int arraySize)
{
int sum(0);
for (int count=0; count<arraySize; count++) {
sum += atoi(date[count]);
}
return sum;
}
int main()
{
char date[] = "131083";
cout << calcNumber(date, sizeof(date) / sizeof(date[0]));
}
The std::atoi function expects a const char* type. When dereferencing a pointer of type const char* with the [] operator you are supplying the char type. That being said what you need there is the std::strlen function to determine the length of your character array -1 to address the \0 null terminating character and your count <= arraySize condition:
#include <iostream>
int calcNumber(const char* date, const size_t arraySize) {
int sum = 0;
for (int count = 0; count <= arraySize; count++) {
sum += date[count] - '0';
}
return sum;
}
int main() {
const char* p = "1234";
std::cout << calcNumber(p, strlen(p) - 1);
}
date[count] is a single char, perhaps '3' (that is ASCII code 51, so it is the same as (char)51).
To convert that into a small number (e.g. 3), use date[count]-'0'
(of course '0' is also a char constant literal, its value is 48 in ASCII; and the ASCII encoding is such that digits glyphs are encoded by consecutive codes).
BTW, you want to stop on a zero byte (terminating every string). So you could use
for (int count=0; date[count] != (char)0; count++) {
sum += atoi(date[count]);
}
then you don't even need to pass any arraySize.
Actually, you are re-inventing (poorly) std::atoi (or strtol). Your calcNumber would handle incorrectly strings like "2X" (but std::atoi("2X") gives 2 which makes more sense). And your calcNumber also behaves badly on "-34" or on " 1"....
I have a few questions:
How do you get a certain char from a string?
How do you get a char to a int?
How do you get a int to a char?
How do you append a char to a string?
I was just making a simple keyed cipher... just playing around to learn cpp. I do know java so if you could relate to that it would be great!
Here is my code so please tell me how to improve... thanks! :)
#include <string>
using namespace std;
string encrypt(string data, string pass) {
// Use a Keyed Cipher //
string encrypted;
int index = 0;
for (int x = 0; x < sizeof(data); x++) {
int tmp = static_cast<int>(data.substr(x));
int tmpPass = static_cast<int>(pass.substr(index));
tmp += tmpPass;
if (tmp > 126) {
tmp -= 95;
}
if (index > sizeof(pass)) {
index = 0;
}
encrypted += static_cast<char>(tmp);
}
return data;
}
How do you get a certain char from a string?
By using index operator. string::operator[]
How do you get a char to a int?
int charToInteger = stringName[i] ;
How do you append a char to a string?
Using string::append
From the link -
string& append ( size_t n, char c );
Appends a string formed by the repetition n times of character c.
First of all with a string: const char& operator[] ( size_t pos ) const; e.g.:
char tmp = encrypted[x];
For conversion, you can just use C-style conversions:
int tmp = (int)encrypted[x];
This should generally work, as long as you're using an architecture with sizeof(char) <= sizeof(int) (e.g. some Texas Instruments calculators :)
But, in your code, you can just operate with chars, because chars can also be used as numeric types.
The easiest way to append a char to string is using += :
string s = "Hello worl";
s += 'd';
How do you get a certain char from a string?
the class "string" implements the operator [], so to get the "i" char you can use mystring[i].
std::string has a function called "c_str()" which returns "const char*" that is inside the string.
so another way to get a char from a std::string is *(mystring.c_str()+i).
How do you get a char to a int?
char is a 1 byte data type, so you can cast char into an int just like in java.
char c = 'a';
int i = (int)c;
How do you get a int to a char?
just like in Java. notice that int is usually 4 bytes (doesn't have to be 4 bytes!!!), so you might lose data because char is 1 byte.
int i=0xFFFF
char c = (char)i;
c is 0xFF! lost some data!
How do you append a char to a string?
std::string implements operator += so you can use it.
string s = "foo"; char c=s[1];
char c = 'a'; int i = c;
int i = 65; char c = (char) i;
string s = "foo"; char c = 'X'; s += c;
for (int x = 0; x < sizeof(data); x++) won't work - use data.size() not sizeof(data)
int tmp = static_cast<int>(data.substr(x)); won't work either. If you want the ascii value of data[x] just do int tmp = data[x];
if (index > sizeof(pass)) won't work - you need to use pass.size()
And finally, you never increase index within the loop, and you return the wrong string.
#include <string>
using namespace std;
string encrypt(string const & data, string const & pass) { // Pass arguments by const reference, not as values which are copied
// Use a Keyed Cipher //
string encrypted;
int index = 0;
for (int x = 0; x < data.size(); ++x) { // Loop over the length of the string, not the size of the string object
int tmp = data[x]; // No need to cast
int tmpPass = pass[index]; // No need to cast
tmp += tmpPass;
if (tmp > 126) {
tmp -= 95;
}
++index; // Remember to loop over the password as well
if (index >= pass.size()) { // Check against length of string, not size of object
index = 0;
}
encrypted += static_cast<char>(tmp);
}
return encrypted; // Return the encrypted string
}
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]);
}