Convert char** to int C++ - c++

So I have an array of symbols which has another array of symbols in it (if i'm not wrong). What I need to do is to change third element (words[2]). This third element will definitely be a number. I have to increase this number by 15 percent. Therefore, I need to convert words[2] to int?
Function:
void create(char* str) {
char** words = new char* [strlen(str)];
int count = 0;
for (char* part = strtok(str, " "); part != NULL; part = strtok(NULL, " ")) {
words[count] = _strdup(part);
count++;
}
cout << "\nNew sentence with edited values:" << endl;
words[2] = words[2] + ((int)words[2] / 100) * 15; //the main problem as I guess
for (int i = 0; i < count; i++) {
printf("%s ", words[i]);
}
cout << endl;
delete[] words;
}
Full code:
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <iomanip>
#include <conio.h>
#include <string.h>
using namespace std;
void create(char*);
void main() {
const int maxLength = 100;
char* str = new char[maxLength];
cout << "Enter sentence:\n";
cin.getline(str, maxLength);
create(str);
delete[] str;
}
void create(char* str) {
char** words = new char* [strlen(str)];
int count = 0;
for (char* part = strtok(str, " "); part != NULL; part = strtok(NULL, " ")) {
words[count] = _strdup(part);
count++;
}
cout << "\nNew sentence with edited values:" << endl;
words[2] = words[2] + ((int)words[2] / 100) * 15;
for (int i = 0; i < count; i++) {
printf("%s ", words[i]);
}
cout << endl;
delete[] words;
}
What it needs to look like (3rd element increased by 15 percent):
Cannot do this using string. Actually, it is my homework from a university and not using string is the condition

you need to convert a char* to int like below. (int) casting won't work
int a = atoi(words[2]); // make sure words[2] is null terminated

Related

How to move word in a circular motion in a string?

I have a string that contains X words (between each word there is a space) I have to move the words in a circular motion to the left according to the number that the user inserts. For example:
"hi my name is aviv and",
the user entered 2. "name is aviv and hi my" I'm looking for legality that repeats itself but I can not find.
Thanks for the guidance. Most importantly, I can not use built-in libraries
Update:
I see there are examples with libraries, I can not use any library.
So what I've done so far.
I wrote a function that gets a string and a number from the user, to move left.
Before sending the string to the function I try to calculate the number of characters I need to move.
My output is - "name is avivhi my"
Regarding the function:
When it gets a string without spaces it works great.
This is my code:
int main()
{
char str[] = "hi my name is aviv";
char str2[] = "hi my name is aviv";
int CountSpace = 0, CountWord = 0;
int Size = 18, flag = 0;
int MoveLeft, Index = 0;
for (int i = 0; str[i] != '\0'; i++)
{
if (str[i] == ' ')
{
CountSpace++;
}
}
CountWord = CountSpace + 1;//Understand how many words there are in a string.
cin >> MoveLeft;
if (MoveLeft >= CountWord)//
{
MoveLeft = (MoveLeft - ((MoveLeft / CountWord) * CountWord));//the size of movment;//To reduce the amount of moves if there is such a possibility
}
for (int i = Size - 1; i >= 0; i--)
{
if (str[i] == ' ')
{
flag++;
}
if (flag == MoveLeft)
{
Index = Size - 1 - (i + 1);//That's the amount of characters I have to move
break;
}
}
MoveLeft = Index;
//This code belongs to the function that accepts a string and the amount to move the characters
for (int i = 0; i < Size; i++)
{
if (i + MoveLeft < Size)
{
str[i] = str2[i + MoveLeft];
}
else
{
str[i] = str2[(i + MoveLeft) - Size];
}
}
cout << "Move Left: " << MoveLeft << endl << str << endl << str2 << endl;
return 0;
}
Here's a hint:
vector<string> words = Your_Code_To_Split_Input_Into_Words();
int count = words.size();
int shift = Your_Code_To_Read_Users_Input();
// print the sentence with the rotation specified by shift
for (int i = 0; i < count; i++)
{
int shifted_index = (i + shift) % count; // modulo math implements circular rotation
string spacing = (i == 0) ? "" : " "; // add a space before each word, except first word
cout << spacing << words[shifted_index];
}
cout << endl;
One possible answer, i highly recommend using vectors instead of regular arrays, it's easy and more dynamic, but i didn't use it because you said you can't use built-in libraries.
#include <iostream>
#include<string>
using namespace std;
int main() {
string a[10000];
int counter = 0;
string b = "hi my name is aviv and";
string temp = "";
int userNum = 2;
for(int i=0;i<b.length() ; i++){
if(b[i]!=' '){
temp+=b[i];
}
else if(b[i]==' ' && temp.length()){
a[counter]= temp;
temp = "";
counter++;
}
}
if(temp.length()){
a[counter] = temp;
}
for(int i=userNum;i<=counter+userNum;i++){
cout<<a[i%(counter+1)]<<endl;
}
}
If you can make use of std::rotate() from <algorithm>, this is much easy to do with that. Parse the words using std::stringstream and store to std::vector. Then apply the shif directly to the vector.
Sample Output: https://www.ideone.com/rSPhPR
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <sstream>
int main()
{
std::vector<std::string> vec;
std::string str = "hi my name is aviv and";
std::string word;
std::stringstream sstr(str);
while(std::getline(sstr, word,' '))
vec.emplace_back(word);
int shift;
std::cout << "Enter the Shift: ";
std::cin >> shift;
std::rotate(vec.begin(), vec.begin() + shift, vec.end());
for(const auto& it: vec)
std::cout << it << " ";
return 0;
}
Here's a snippet :
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
#define MaxWords 10
int main()
{
stringstream ss;
ss.str("hi my name is aviv and");
string str[MaxWords];
int i;
for (i =0; std::getline(ss, str[i],' ');i++ )
{
cout << str[i] << " ";
}
int n;
cout << "\nEnter pos to split : ";
cin >> n;
for (int j = n; j <= i; j++)
{
cout << str[j] << " ";
}
for (int j = 0; j < n; j++)
{
cout << str[j] << " ";
}
cout << endl;
return 0;
}
Output:

No output after using strcmp()

I'm trying to make a program that asks the user to input a string then checks to see how many vowels and consonants are in the string, using c strings. Right now I'm working on the function that counts the vowels. I finally got it to were I don't have any errors, but my program just hangs up after choosing to count the vowels. Here is my code.
#include "stdafx.h"
#include <iostream>
#include <string.h>
using namespace std;
class VowelsandConsonants {
public:
int findVowels(char *cString, const int STRINGLEN) {
const int SIZE = STRINGLEN;
int vowelCount = 0;
char *str = cString;
char vowels[5] = { 'a', 'e', 'i', 'o', 'u' };
for (int i = 0; i < SIZE; i++) {
str[i];
for (int j = 0; j < SIZE; i++) {
vowels[j];
if (strcmp(vowels, str)) {
vowelCount++;
}
}
}
return vowelCount;
}
};
int main()
{
char *myString = nullptr;
const int STRLEN = 20;
int selection;
myString = new char[STRLEN];
VowelsandConsonants v;
cout << "Enter a string 20 characters or less." << endl;
cin.getline(myString, STRLEN);
cout << "Select the number of what you want to do." << endl;
cout << "1.) Count the number of vowels." << endl;
cout << "2.) Count the number of consonants." << endl;
cout << "3.) Count both vowels and consonants." << endl;
cout << "4.) Enter another string." << endl;
cout << "5.) Exit program." << endl;
cin >> selection;
if (selection == 1) {
cout << v.findVowels(myString, STRLEN);
}
delete[] myString;
return 0;
}
Am I approaching this the right way?
I recommend using a C-Style string containing the vowels, then using strchr to search it:
const char vowels[] = "aeiou";
const size_t length = strlen(cString);
unsigned int vowel_count = 0;
for (unsigned int i = 0; i < length; ++i)
{
if (strchr(vowels, cString[i]) != NULL)
{
++vowel_count;
}
}
There are other methods, such as using an array to hold the counts (and using the letter as an index) or std::map.

why isnt working my function to concatenate?

I've tried so many times in different way to concatenate two strings, one way gives me segment fail,and the other way don't give me error but not it's making the correct function of concatenate. I need result is like this aa, what am I doing wrong?
#include <iostream>
using namespace std;
char str1[20], str2[20], str3[20];
void stringConcat(char[], char[], char[]);
void stringConcat(char str1[], char str2[], char str3[])
{
int i = 0, j = 0;
if (str1[i] != '\0') {
str3[i] = str1[i];
i++;
}
if (str2[j] != '\0') {
str3[i + j] = str2[j];
j++;
}
str3[i] = '\0';
}
int main()
{
int compare;
cout << "First string" << endl;
cin >> str1;
cout << "Second string" << endl;
cin >> str2;
stringConcat(str1, str2, str3);
cout << "result: " << str3 << endl;
return 0;
}

C++ string confusion

I would like to say thanks for your patience to before hand. I am just starting to learn how to code with some background knowledge from a 101 cs course I took beforehand, so I may be making some fundamental mistakes. Here is the question I am trying to solve:
Find the greatest product of five consecutive digits in the 1000-digit number.
73167176531330624919225119674426574742355349194934
96983520312774506326239578318016984801869478851843
85861560789112949495459501737958331952853208805511
12540698747158523863050715693290963295227443043557
66896648950445244523161731856403098711121722383113
62229893423380308135336276614282806444486645238749
30358907296290491560440772390713810515859307960866
70172427121883998797908792274921901699720888093776
65727333001053367881220235421809751254540594752243
52584907711670556013604839586446706324415722155397
53697817977846174064955149290862569321978468622482
83972241375657056057490261407972968652414535100474
82166370484403199890008895243450658541227588666881
16427171479924442928230863465674813919123162824586
17866458359124566529476545682848912883142607690042
24219022671055626321111109370544217506941658960408
07198403850962455444362981230987879927244284909188
84580156166097919133875499200524063689912560717606
05886116467109405077541002256983155200055935729725
71636269561882670428252483600823257530420752963450
I will write the error I am receiving first:
I get the following error when I call the findmax function that I've created:
error: could not conver '(std::string*)(&arr)' from 'std::string* {aka
std::basic_st...}
And here is my code I've written so far:
#include <iostream>
#include <string>
using namespace std;
void findmax(string test);
int main()
{
int assignNum = 0;
int n2;
string p = "7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450";
string arr[995];
string plast = "";
//FOR LOOP TO LIST ALL CONSECUTIVE INTEGERS OF 5 DIGITS
for (assignNum = 0; assignNum < 995; assignNum++) { //Sliding up initial digit
plast = "";
for (int j =0; j<5; j++) {
plast = plast + p[assignNum + j];
}
arr[assignNum]= plast;
}
cout << sizeof(arr)/sizeof(arr[0]) << endl;
findmax(arr); // THE ERROR REFERS TO HERE ******!!!!!!
}
//FIND MAX FUNCTION USING RECURSION
void findmax(string test) {
string right="";
int k;
int stringSize = sizeof(test)/sizeof(test[0]);
int middle = (sizeof(test)/sizeof(test[0]))/2;
for (k=0; k<=stringSize; k++){
if (test[k] >= test[middle]){
right = right + test[k];
}
else {
cout << "do nothing " << endl;
}
if (stringSize != 2){
findmax(right);
}
else {
if (test[0] >= test[1]){
cout << test[0]<< endl;
break;
}
else {
cout << test[1] << endl;
break;
}
}
}
}
Any help would be greatly appreciated, I've been working on this for quite a while and really want it to work.
For anyone interested, I solved the problem, which I actually misread at the start. Here is my code (without trying to use recursion):
#include <iostream>
#include <string>
#include <stdio.h> /* printf, fgets */
#include <stdlib.h> /* atoi */
#include <math.h>
using namespace std;
void findmax(string test[]);
int main()
{
int assignNum = 0;
int n2;
int ntp;
int ltp = 0;
string p = "7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450";
string pnew = "";
//FOR LOOP TO LIST ALL CONSECUTIVE INTEGERS OF 5 DIGITS
for (assignNum = 0; assignNum < 995; assignNum++){ //Sliding up initial digit
pnew = "";
for (int j =0; j<5; j++){
pnew = pnew + p[assignNum + j];
}
string myString = pnew;
int value = atoi(myString.c_str()); //value = 45
ntp = ((value / 10000) % 10) *((value / 1000) % 10) * ((value /100) % 10) * ((value / 10)% 10) * ((value / 1) % 10);
cout << (value / 10000) % 10 << endl;
cout << (value / 1000) % 10 << endl;
cout << (value / 100) % 10 << endl;
cout << (value / 10) % 10 << endl;
cout << (value / 1) % 10 << endl;
cout << "this is ntp: " << ntp << endl;
if (ltp>=ntp){
cout << "ltp: " << ltp << "is >= ntp: " << ntp << endl;
}
else {
cout << "ntp: " << ntp << "is > ltp: " << ltp << endl;
ltp=ntp;
}
cout << ltp << endl;
}
cout << "THE LARGEST CONSECUTIVE 5 DIGIT PRODUC IS: " << ltp << endl;
}
Answer: 40824
execution time: .986s
findmax expects a string, but you're feeding it a string [].
You can fix the prototype and the signature:
void findmax(string test[]);
void findmax(string test[]) {
But you do it in another location:
string right="";
// ...
findmax(right); // right is not an array
I suspect your intention is something like this:
std::string res = ""; // build string out of array
for (int i = 0; i < sizeof(arr)/sizeof(arr[0]); i++)
res += arr[i];
findmax(res);
But I get a segmentation fault, so there is something wrong with your algorithm regardless.
p is one std::string variable that is instantiated using the (const char *) value.
arr is an array of std::string that can hold up to 995 independent std::string values. findmax is a function returning void that accepts a copy of std::string value. So when you try passing arr to findmax, the compiler which only knows about a findmax that accepts std::string gets confused on being invoked with an array of std::string.
You are probably getting confused with the std::string being initialized with a char [] or char *. 73167176531330624919225 ... can either be treated as a char arr[995] or a char *arr with the appropriate code modifications so that when findmax is invoked, a std::string object gets constructed.
PS: Also, when passing around non-pod values to functions you are better off passing them as a reference as to avoid unnecessary copying:
void findmax(std::string & test) // If you want to manipulate value in function
OR
void findmax(const std::string & test) // To avoid surprises in client code

Code can run but doesn't show the Result in Eclipse.?

Why the example code below can run fine on Visual Studio. In Eclipse, NetBean or CodeBlock the code can run but can't show the Result? Thanks All.
Ex: input one string.
a/ Uppercase first letter.
b/ Remove spaces inside the string.
#include "iostream"
#include "string.h"
using namespace std;
#define MAX 255
//uppercase first letter
char* Upper(char* input)
{
char* output = new char[MAX];
bool isSpace = false;
for (int i = 0; i < strlen(input); i++)
{
output[i] = input[i];
if (isSpace)
{
output[i] = toupper(output[i]);
isSpace = false;
}
if (output[i] == ' ') isSpace = true;
}
output[strlen(input)] = '\0'; // end of the string
output[0] = toupper(output[0]); // first character to upper
return output;
}
//remove space inside the string
char* RemoveSpaceInside(char* input)
{
char* output = new char[MAX];
strcpy(output, input);
int countWhiteSpace = 0;
for (int i = 0; i < strlen(output); i++)
{
if (output[i] == ' ')
{
for (int j = i; j < strlen(output) - 1; j++) // move before
{
output[j] = output[j + 1];
}
countWhiteSpace++;
}
}
output[strlen(output) - countWhiteSpace] = '\0'; // end of the string
return output;
}
int main()
{
char* name = new char[MAX];
cout << "Enter name: "; cin.getline(name, strlen(name));
cout << "Your name: " << name << endl;
cout << "\n******* Q.A *******\n";
char* qa = Format2VN(name);
cout << qa << endl;
cout << "\n******* Q.B *******\n";
char* qb = RemoveSpaceInside(name);
cout << qb << endl;
return 0;
}
char* name = new char[MAX];
cout << "Enter name: ";
cin.getline(name, strlen(name));
Calling strlen(name) will invoke undefined behavior, because you haven't initialized the array. Poor strlen will try to find the NUL character in an uninitialized byte mess. Definitely not a good idea.
What you probably want is:
cin.getline(name, MAX); // not sure if MAX or MAX-1 or whatever
In general, do yourself a favor and replace char* with std::string. Also, get a good C++ book.
Here is how your example would look like in actual C++:
#include <algorithm>
#include <cctype>
#include <iostream>
#include <string>
std::string upper_first_letter(std::string s)
{
if (!s.empty()) s[0] = toupper(s[0]);
return s;
}
std::string remove_spaces(std::string s)
{
s.erase(std::remove_if(s.begin(), s.end(), isspace), s.end());
return s;
}
int main()
{
std::string name;
std::cout << "Enter name: ";
std::getline(std::cin, name);
std::cout << name << '\n';
std::cout << upper_first_letter(name) << '\n';
std::cout << remove_spaces(name) << '\n';
}