How to Pass a String in a function? - c++

I have a function (int, string) in Main:
string word("HELLO");
int x = 0;
char choice;
swap(x, word);
I am trying, with no success, to pass into the following function:
void swap(int, string) {
int x = 0;
string word = "HELLO";
cout << "Would you like to change a letter? Please enter the letter
position. " << endl;
cin >> x;
if (x == 1) {
cout << "What do you want to change it to?" << endl;
cin >> word[0];
I keep getting this error:
Error C2664 'void std::swap(std::exception_ptr &,std::exception_ptr &) throw()': cannot convert argument 1 from 'int' to 'std::exception_ptr &'
What gives?

The main problem with your code is the indentation. Your code is not readable and mostly hard to comprehend it. Beautify it. Write nice, readable and a structured code. You can read more about indentation at the following link.
https://en.wikipedia.org/wiki/Indentation_style
The next thing is the function declaration. You do not declare your function before defining it. The function declaration should be top of the main function and definition of the function should be below the main function.
You can find more info about the function declaration at the following link:
http://en.cppreference.com/w/cpp/language/function
Since you are not using a char array to print out the string, it is useless to go through the string with a loop. Include the <string> library and start to work towards the string type. By passing the string variable inside std::cout is enough to print out the string.
Lastly, since you are trying to manipulate a string variable outside the main function, it is required that you are passing a reference parameter instead.
void myFunction(std::string& parameter);
This way, the original variable that exists inside the main or inside any other function will be altered. Without the reference, &, the value you are trying to modify will not be changed.
The following link demonstrates the use of reference.
http://www.learncpp.com/cpp-tutorial/73-passing-arguments-by-reference/
Please read my comments below of why some changes were applied. I made crafty changes to the change function. You are now eligible to work towards any
string type with any size.
#include <iostream>
#include <string> //When you are working on strings, use the string library.
using namespace std;
//Function declaration is very important. Have the declarations above main.
void change(string&);
int main() {
string word("HELLO");
char choice;
cout << "The word is : " << endl;
cout << word << endl;
//No need for the for loop to print out the string as
// we are working on a string and not a char array.
// for (int i = 0; i < word.length(); i++) {
// cout << word[i];
// }
change(word);
cout << "The new word is" << endl << word << endl;
cout << "Would you like to enter another change ? Enter Y or N ? " << endl;
cin >> choice;
if (choice == 'y' || choice == 'Y') {
change(word);
cout << word << endl;
}
else {
cout << "Good Bye" << endl;
}
system("pause");
return 0;
}
//When your datatype is to be modified outside the function, use the reference
//parameter type '&'.
//Without the reference type, your modified version of the type will only be modified
//inside that function.
//The original one will not be altered.
void change(string& word) {
/*
* size_t is simply unsigned int, to work towards manipulation and accessing
* of string types, use unsigned int or std::size_t
*/
size_t x = 0;
cout << "Would you like to change a letter? Please enter the letter position. " << endl;
cin >> x;
//Check to see if the inputted value is within the string length range.
if(x > 0 && x <= word.length())
cout << "What do you want to change it to?" << endl;
else{
cout << "The entered position is outside the string size range\n";
return; //Quit from the function if the condition is not met.
}
/*
* Instead of using if/else if statements,
* Just make a normal loop. Much simpler.
*/
for(size_t i = 0; i < word.length(); i++){
if((x-1) == i)
cin >> word[i];
}
}

Related

C++ executes blanks after class creation

I'm trying to learn C++ to help my sibling with their assignment. So I'm attempting the assignment. It's a simple program to load a dictionary test file with words, their type, and definition to an array of Word type objects. I was able to get started with a normal string array instead of an object array as requested. But as soon as I defined the Word class and the array the code builds without an issue. When I try to run the code the cursor simply blinks for a few seconds and returns to the normal terminal.
Am I doing something wrong with my Class constructor ??
#include <fstream>
#include <string>
using namespace std;
class Word {
public:
string WordEntry;
string Type;
string Definition;
//constructor
Word(string word, string type, string definition){
WordEntry=word;
Type=type;
Definition=definition;
}
};
int main(){
cout << "Test1";
Word *wordArray[318555];
int count=0;
string word, type, definition,blank;
cout << "TEST" << count << "\n";
ifstream file("dictionary2021 (1).txt");
if (file.is_open()){
cout << "File dictionary2021.txt has been opened \n";
while (!file.eof()){
getline(file,word);
getline(file,type);
getline(file,definition);
getline(file,blank);
wordArray[count]= new Word(word,type,definition);
count++;
}
file.close();
cout << "File dictionary2021.txt has " << count/3 << " entries\n";
}
cout << "TEST" << count << endl;
cout << cc;
int selection;
string input;
cout << "Function List - Please hit Enter after your selection \n";
cout << " 1. Word Search \n 2. Repetitive z search \n 3. Wild Card Search\n";
cout << "Selection:";
cin >> selection;
if(selection=1){
cout << "Enter word:\n";
cin >> input;
string str("a");
for (int i = 0; i < 12; i+3)
{
cout << "1";
if (input.compare(str)== 0)
{
cout << wordArray[i+1];
return 0;
}
cout << "2";
}
}
}```
Word* wordArray[318555]; is a huge value and we're talking about 2548440 bytes (or roughly 2.4MB). This might be too large for a single stack frame and can easily be inefficient.
What I suggest is to use std::vector to store the word array and use std::vector<>::push_back() method to insert data to it.
Note: In your code snippet your not deallocating the Word object pointers once everything is done. Either explicitly delete those pointers using delete or use a smart pointer like std::unique_ptr.

C++ Replacing a character in an array without the use of C-String Library Functions

I was given a set of questions, basically asking me to recreate the utility of certain library functions such as strlen() and strcpy() without using them.
However, one of the questions has gotten me stumped. It's a function that replaces a character in a string with anything you choose.
Example :
Str : marix xdyssey
target : x
replacement : o
Output : mario odyssey
This is what I have right now
#include <iostream>
using namespace std;
int replace(char *s2, char target, char replacementChar);
const int MAX_SIZE = 128;
int main()
{
char str2[MAX_SIZE], target, replacement;
int change;
cout << "Enter your string : " << endl;
cin.getline(str2, MAX_SIZE);
cout << "What's your target?" << endl;
cin >> target;
cout << "What do you want to replace it with?" << endl;
cin >> replacement;
replace(str2, target, replacement);
}
int replace(char *s2, char target, char replacementChar)
{
int change = 0;
for(int i=0; s2[i]!='\0'; i++)
{
if(s2[i] == target)
{
swap(s2[i], replacementChar);
change++;
}
}
cout << "There were " << change << " change(s)." << endl;
cout << s2;
return change;
}
And even though "change" returned 2, I was given the output of "mario xdyssey".
Any advice or hints as to how to proceed would be greatly appreciated.
Change
swap(s2[i], replacementChar);
to:
s2[i] = replacementChar;
swap() exchanges the values of the two variables, so after the first replacement, replacementChar contains the same thing as target, so nothing gets updated.

Retrieve all data via void function

Been trying to find a way through this. I am new to C++ and creating a simple program to get the user data, validate and cout to the screen. What i'm trying to do is to have the one function use pointers to get the users input and display back to them. This may have been answered before but I haven't had much luck finding it.
So far i have the below code
#include <iostream>
using namespace std;
void userData(int&);
int main(){
int a = 0;
int * kmpointer;
int * dayspointer;
userData();
cout << "You ran " << userData(kmpointer) << endl;
cout << "in " << userData(dayspointer) << "days!!" <<endl;
}
void userData(int& i){
cout << "Enter how Many Km's you ran:";
while (true)
{
cin >> kmpointer;
if ((cin) && (kmpointer >= 0) && (inputYear <= 100))
break;
cin.clear();
cin.ignore( 100, '\n' );
cout << "That can't be right!\n";
cout << "Enter how Many Km's you ran:";
}
cout << "How many days in a row did you run?";
while (true)
{
cin >> dayspointer;
if ((cin) && (dayspointer >= 1) && (dayspointer <= 100))
break;
cin.clear();
cin.ignore( 1000, '\n' );
cout << "Thats way to much!";
cout << "How many days in a row did you run? ";
}
}
IMO, you should start with some reading about C++. You are missing some basic concepts and trying too complex exercises for your level.
1
function is not declared/defined.
2
userData is declared accepting a parameter, but used without.
3
The problem you face is related probably with what we call scope: A variable is only existing and visible within its scope (usually enclosed by { and }.
In your case, kmpointer and dayspointerare only visible within the main function and thus, you cannot use them in userData.
To solve that, I suggest you to pass those variables as parameters for userData.
4
Pointers, references, values: They are different. You are saving the user input as a pointer address, which is indeed problematic.
General
In general, your code is full of mistakes. Try a Hello world! and continue from there steps by steps.
Focussing on the specific question you asked (though as observed you have other problems in your code), don't use pointers, use references.
Before we get to that this
cout << "You ran " << userData(kmpointer) << endl;
won't compile, since as you know userData is a void function, so applying << to it makes no sense. It's void so there's nothing to stream.
You said you wanted to pass parameters into the function and let them be changed so do that. Then display the variables afterwards. (Not the "result" of a void function call).
Correctly getting the user input is a separate question which has been answered before.
#include <iostream>
using namespace std;
void userData(int& i, int& j, int& k);
int main() {
int a = 0;
int kmpointer;
int dayspointer;
//Here we call our function, ONCE
userData(a, kmpointer, dayspointer);
//Here we display what values we now have
//after calling the function, ONCE
cout << "You ran " << kmpointer << endl;
cout << "in " << dayspointer << " days!!" << endl;
}
//simplified to demonstrate changes to the reference parameters
void userData(int& i, int& j, int& k) {
//Here we have three parameters which we refer to as i, j and k
// They may have different names ousdie in the calling code
// but this function (scope) neither knows nor cares
j = 42;
k = 101;
}

Assigning the "Enter Key" value to a string [C++]

In this rather simple exercise I have to receive an user input, store said input into a string, pass the string to a function by reference and finally modify the string so that every character is "parsed" by the toupper() function.
However, should the user insert 'q' as input, the program stops saying "Bye" OR if he just presses the Enter Key, the program is supposed to say something like "Hey, this string is empty".
Now the real problem here is in the last part since my code won't manage the case where the user inputs only the Enter Key value (to be honest, even if I just text a bunch of spaces followed by the Enter Key, nothing happens)
void uppercase(std::string &);
int main(){
using namespace std;
string ex2;
cout << "Exercise 2" <<endl;
while(ex2!="Bye"){
cout << "Enter a string(q to quit): ";
cin >> ex2;
cout << "Was: " << ex2 << endl << "Now is: ";
uppercase(ex2);
}
return 0;
}
void uppercase(std::string &str){
using namespace std;
if(str[0]=='\n')
cout <<"Empty string dude!" << endl;
else{
if(str.length()==1 && str[0]=='q'){ //press 'q' to exit program
str="Bye";
cout << str;
}
else{ //uppercase
for(int i=0;i<str.length();i++){
str[i]=(toupper(str[i]));
}
cout << str <<endl;
}
}
}
I also tried the compare() function and even to compare the whole string to null (pointless, but still worth a shot) and to the string "";
Sorry for the bad interpretation of your problem, trying
if( (str.length()==1 && str[0]=='q') || str.length() == 0)
{}
May help you out of the problem

Defining correct parameters & Passing an array in a recursive function C++

I am in an intro C++ class and I've had difficulties with defining correct parameters before, so if someone could point out what I'm doing wrong that would be great.
This assignment was to create a binary search function, in which the program will guess a number that the user is thinking of.
Here is the code I have:
#include <iostream>
using namespace std;
int b_search(int Arry[], int L, int R)
{
int M = 0;
char userAnswer = '-';
M = (L + R) / 2;
cout << "Is it " << Arry[M] << "? (l/h/z): ";
cin >> userAnswer;
if( (userAnswer != 'l') && (userAnswer != 'h') ) {
cout << "Thank you!" << endl;
}
else {
if (userAnswer == 'l') {
b_search(Arry[], L, M);
}
else {
b_search(Arry[], ++M, R);
}
}
return;
}
int main()
{
const int N = 100;
int A[N];
int i = 0;
int value = 1;
for(i = 0; i < N; ++i)
{
A[i] = value;
++value;
}
cout << "Choose a number from 1 to 100." << endl << endl;
cout << "Answer with:" << endl;
cout << " l - if your num is lower" << endl;
cout << "or: " << endl;
cout << " h - if your num is higher" << endl;
cout << "or: " << endl;
cout << " any other key if the guess is right." << endl << endl;
b_search(N, 1, 100)
return 0;
}
When I compile this it has a problem with the first recursive call's 1st parameter.
This is the error message from Code Pad:
In function 'int b_search(int*, int, int)':
Line 22: error: expected primary-expression before ']' token
compilation terminated due to -Wfatal-errors.
Thank you!
You don't use the square brackets when referring to an array by its name. Let's say you declare an array called A. Then:
A: is an array.
A[5]: is an element of A.
A[]: is not a valid expression.
Since you want to pass the array to the b_search function recursively, rather than any of its elements, just use Arry.
The int Arry[] in the function declaration is not an expression, but a declarator which declares the parameter Arry. Declarators resemble expressions in some ways, but have different syntax rules. [] means "array" in a declarator, but not in an expression.
There is a subtlety here associated with array parameters: when you declare a function to take an array parameter, the parameter's type is automatically rewritten to become a pointer instead. So Arry is actually a pointer, rather than an array. This detail is invisible to you in this case because arrays and pointers behave in the same way under subscripting and arrays are automatically converted to pointers when passed by value.
You define b_search as taking in an int array, an int, and another int. However, the first thing you do:
b_search(N, 1, 100); // Is invalid since N is an int but the function expects an array.
is try to pass in a const int, an int, and an int. The first parameter is supposed to be an int array, not an int.
The other problem I see is inside the definition of your b_search where you try to recurs, you call b_search with the first parameter Arry[]. The brackets are not valid, since Arry is already an array, you can just pass it in as is.