i'm trying to pass a char[] to another function, but for some reason I keep getting weird outputs but have no errors. I have the following methods:
void storeKey()
{
char keyArray[10];
cout << "Please enter 10bit key" << endl << "==> ";
cin >> keyArray;
storePlaintext(keyArray);
cout << keyArray << endl;
}
void storePlaintext(char key[])
{
char plaintextArray[8];
cout << "Please enter 8bit plaintext" << endl << "==> ";
cin >> plaintextArray;
cout << plaintextArray << endl << key[1] << endl;
//cout << plaintextArray << endl << key << endl;
}
I should get a print out of: 00000000 and 1111111111 on the next line followed by 1111111111
But I get 0000000 then "c" (or something random) followed by 111111111. WHY is this happening? I should be able to pass a array like i'm doing with no problem right? I need to be able to pass arrays from function to function and use the data inside them. ANY help will be much appreciated. Thanks
Use std::string.
#include <string>
#include <fstream>
#include <iostream>
using namespace std;
void storePlaintext(const string& key);
void storeKey()
{
std::string keyArray;
cout << "Please enter 10bit key" << endl << "==> ";
getline(cin, keyArray);
storePlaintext(keyArray);
cout << keyArray << endl;
}
void storePlaintext(const string& key)
{
string plaintextArray;
cout << "Please enter 8bit plaintext" << endl << "==> ";
getline(cin, plaintextArray);
if ( key.size() > 1 )
cout << plaintextArray << endl << key[1] << endl;
}
Note the use of std::string, std::getline, and passing parameters by (const) reference. Also, the check to ensure that the key has more than 1 character is done, since accessing key[1] with a string of length 1 or less is undefined behavior.
Related
This is part of my project codes.
About the struct customer that I did, from welcomeScreen function I call the getInfo function for user to input the details (as you can see) and then return back the value to welcomeScreen function for output.
I can compile the codes, but the problem is there is no output for all the details after I input it (just blank)? Sorry if this is a dumb question cause im still a student.
struct customer
{
string name;
string email;
int number;
};
void welcomeScreen(); //prototype
void getInfo(struct customer cust); //prototype
void welcomeScreen()
{
struct customer cust; // struct declaration
const int SIZE=5;
system("CLS");
cout << setfill ('-') << setw (55) << "-" << endl;
cout << "\tWelcome to Computer Hardware Shop" << endl;
cout << setfill ('-') << setw (55) << "-" << endl;
cout << endl << "Type of hardwares that we sell:" << endl;
string item[SIZE]={"Monitor","CPU","RAM","Solid-State Drive","Graphic Card"};
for(int i=0;i<SIZE;i++)
cout << "\t" << i+1 << ". " << item[i] << endl;
getInfo(cust);
cout << endl;
cout << fixed << showpoint << setprecision (2);
cout << "Name: "<< cust.name << endl; // struct output
cout << "Email: "<< cust.email << endl;
cout << "Phone Number: " << cust.number << endl;
cout << endl;
}
void getInfo(struct customer cust)
{
cout << endl << "Enter name: ";
cin >> cust.name;
cout << "Enter email: ";
cin >> cust.email;
cout << "Enter phone number: ";
cin >> cust.number;
}
You probably want to pass a pointer or a reference, in this case recommend a reference because it means fewer changes to your code:
void getInfo(struct customer &cust); //prototype
Remember to change your function parameter as well.
Okay, I am trying to use the code:
getline(cin, phrase);
When I compile I get the error:
no matching function for call to 'getline'
Here is the full code:
#include <iostream>
#include <cstring>
#include <string>
using namespace std;
int main()
{
cout << "Challenge 1\n" << "Kaitlin Stevers\n" << "Characters and Strings" << endl;
cout << endl;
cout << endl;
char letter[2];
cout << "Please enter a letter: " << endl;
cin >> letter;
cout << "You entered: " << letter << endl;
char word[5];
cout << "Please enter a word up to 5 characters long: " << endl;
cin >> word;
cout << "The word you entered is: " << word << endl;
char phrase[100];
cout << "Please enter a phrase up to 99 characters long: " << endl;
getline(cin, phrase);
cout << "The phrase you entered is: " << phrase << endl;
string lettero;
cout << "Enter one letter: " << endl;
cin >> lettero;
cout << "The letter you entered is: " << lettero << endl;
string wordo;
cout << "Please enter a word: " << endl;
cin >> wordo;
cout << "The word you entered is: " << wordo << endl;
string phraseo;
cout << "Please enter five words: " << endl;
getline(cin, phraseo);
cout << "The words you entered are: " << phraseo << endl;
return 0;
}
'no matching function call for getline', cause getline takes a string not a char[] as argument. See cin.getline() if you absolutely want to pass a cha[] as argument.
As you see here.
This getline(cin, string) function accepts a string.
Although, there is also an instruction you can use to put the line into a char array like so:
char phrase[99];
cin.getline (phrase,99);
Or you could also get the input into a string, then convert it to a char array :
string temp = "";
cin >> temp;
char phrase[99];
strcpy(phrase, temp.c_str());
So here I have a class definition of a Car and then I create a carObject with it. I want the user to input values for all the variables in the carObject. As you see here, I have managed to get user input, but my approach to this problem is inefficient in my opinion.
I notice that all of the user inputs, except for the first one are very similar. I would like to use a loop of some kind to iterate over the declaration statements, or blocks of statements, and change the variable every time. I would like to put an if statement to enter different input only for the first iteration of the loop. I know that in bash I could use a string variable to stand for the variable name, but I don't know if that's possible in C++.
Notice that the object name does not change, but only the variables that are associated with it. I also use the same word for the user input, which preferably should be changed every iteration. I also have a series of arrays which are named similarly. The purpose of these arrays is to tell the user what options are available for a particular variable.
Although I have previous programming experience, I am relatively new to C++. A block of code that would serve as a solution to my problem that involves a call to another function would suit my purposes. Here is my code below.
#include <iostream>
#include <string>
using namespace std;
class Car {
public:
string Name;
string Model;
string Color;
string Transmission;
string Category;
};
int main() {
Car CarObject;
string modelOptions [3] = { "Ferrari", "Porsche", "Nissan" };
string colorOptions [4] = { "Blue", "Red", "Green", "White" };
string transmisionOptions [2] = { "Automatic", "Manual" };
string categoryOptions [3] = { "A", "B", "C" };
cout << "Enter " << "name" << " for Car 1." << endl;
cin >> carObject.Name;
cout << endl;
cout << "Enter " << "model" << " for Car 1." << endl;
cout << "Options are:";
for (const string &text: modelOptions) {
cout << " " << text;
}
cout << "." << endl;
cin >> carObject.Model;
cout << endl;
cout << "Enter " << "color" << " for Car 1." << endl;
cout << "Options are:";
for (const string &text: colorOptions) {
cout << " " << text;
}
cout << "." << endl;
cin >> carObject.Color;
cout << endl;
cout << "Enter " << "transmission" << " for Car 1." << endl;
cout << "Options are:";
for (const string &text: transmissionOptions) {
cout << " " << text;
}
cout << "." << endl;
cin >> carObject.Transmission;
cout << endl;
cout << "Enter " << "category" << " for Car 1." << endl;
cout << "Options are:";
for (const string &text: categoryOptions) {
cout << " " << text;
}
cout << "." << endl;
cin >> carObject.Category;
cout << endl;
...
return 0;
}
void Car::InputParameter(string& param, const string &msg, const vector<string>& options)
{
cout << msg << endl;
for (const string &text: options) {
cout << " " << text;
}
cout << "." << endl;
cin >> param;
cout << endl;
}
I think you might want something like this. You just call it for each member.
This block of code:
cout << "Enter " << "category" << " for Car 1." << endl;
cout << "Options are:";
for (const string &text: categoryOptions) {
cout << " " << text;
}
cout << "." << endl;
cin >> carObject.Category;
cout << endl;
… can be replaced with a call to a function like this:
carObject.Category = userInput( "category", categoryOptions );
Clearly it returns a string (that is, a std::string).
The options argument should better be made a vector<string>.
Then just replace the other similar blocks with ditto calls to that function.
Is it a good idea to make that function a member function of Car?
No.
Consider, for example, how to then use Car in a GUI program (Graphical User Interface).
Okay so as the title said its refusing to execute the stuff right under the "do" function even though as far as i can tell all the parameters for a repeat have been fulfilled. So far what i get when i run the program is something along the lines of...
"Would you like to search another name?
Please enter Y for yes and n for no:"
looping over and over when i press y
#include <iostream>
#include <string>
#include <iomanip>
#include <vector>
#include <algorithm>
#include <cstdlib>
using namespace std;
int main()
{
vector <string> vName, vID, vClass;
string sName, sID, sClass, sSearch, cQuestion;
int iSize, iStudent;
// Display initial vector size
iSize = vName.size();
cout << "Student list starts with the size:" << iSize << endl;
// Get size of list from user
cout << "How many students would you like to add?" << endl;
cin >> iStudent;
cin.ignore();
// Get names, ids, and classes
for (int i = 0; i < iStudent; i++)
{
cout << "Student" << i + 1 << ":\n";
cout << "Please enter the student name: ";
getline(cin, sName);
vName.push_back(sName);
cout << "Enter ID number ";
getline(cin, sID);
vID.push_back(sID);
cout << "Enter class name ";
getline(cin, sClass);
vClass.push_back(sClass);
}
// Display header
cout << "The list of students has the size of: " << iStudent << endl;
cout << "The Student List" << endl;
cout << "\n";
cout << "Name:" << setw(30) << "ID:" << setw(38) << "Enrolled Class : " << endl;
cout << "--------------------------------------------------------------------------";
cout << "\n";
// for loop for displying list
for (int x = 0; x < vName.size() && vID.size() && vClass.size(); x++)
{
cout << vName[x] << "\t \t \t" << vID[x] << "\t \t \t" << vClass[x] << endl;
}
// Sorting function
cout << "\n";
cout << "The Student List after Sorting:" << endl;
cout << "\n";
sort(vName.begin(), vName.end());
for (int y = 0; y < vName.size(); y++)
{
cout << vName[y] << endl;
}
cout << "\n";
// Search function
do
{
cout << "Please Enter a name to be searched:" << endl;
getline(cin, sSearch);
if (binary_search(vName.begin(), vName.end(), sSearch))
{
cout << sSearch << " was found." << endl << endl;
}
else
{
cout << sSearch << " was not found." << endl << endl;
}
cout << "Would you like to search another name?" << endl << endl;
cout << "Please enter Y for Yes and N for No:" << endl << endl;
cin >> cQuestion;
} while (cQuestion == "Y" || cQuestion == "y");
cout << "Thank you for using this program!" << endl;
return 0;
}
Edit:
Posted whole program, please excuse any grammatical mistakes, I'm just trying to get the program down before i go in there and make it pretty.
The tail of your loop does this:
cout << "Please enter Y for Yes and N for No:" << endl << endl;
cin >> cQuestion;
which will consume your string if you entered one, but leave the trailing newline in the input stream. Thus when you return to the top of the loop after entering Y or y, and do this:
cout << "Please Enter a name to be searched:" << endl;
getline(cin, sSearch);
the getline will extract an empty line.
How to consume the unread newline from the input stream is up to you. You will likely just end up using .ignore() as you did prior in your program. Or use getline to consume cQuestion. You have options. Pick one that works.
And as a side note, I would strongly advise you check your stream operations for success before assuming they "just worked". That is a hard, but necessary, habit to break. Something like this:
do
{
cout << "Please Enter a name to be searched:" << endl;
if (!getline(cin, sSearch))
break;
if (binary_search(vName.begin(), vName.end(), sSearch))
{
cout << sSearch << " was found." << endl << endl;
}
else
{
cout << sSearch << " was not found." << endl << endl;
}
cout << "Would you like to search another name?" << endl << endl;
cout << "Please enter Y for Yes and N for No:" << endl << endl;
} while (getline(cin,cQuestion) && (cQuestion == "Y" || cQuestion == "y"));
If cQuestion is a char array then you need to use strcmp or stricmp to compare it with another string i.e. "Y" and "y" in this case. If cQuestion is a single char then you need to compare with 'Y' and 'y' (i.e. with a single quote)
Strings in C++ are not first class types therefore they do not have some of the string operation that exist for other basic types like ints and floats. You do have std::string as part of the standard C++ library which almost fulfills the void.
If you just change the type of cQuestion to std::string your code should work but if you want to stick with chars then you will need to change the quote style.
I'm a beginner in c++ so I'm just messing around with some stuff while reading articles and books. But I spent 20 minutes re-reading this over and over again and I can't tell what's wrong with it.
#include <iostream>
#include <string>
using namespace std;
int main ()
{
cout << "Hello there, this is your personal simple calculator.";
cin.get();
cout << "Type in what you want to do. (Addition, Subtraction, Multiplication, Division)"<< endl;
string c;
getline (cin, c);
if (c == "Addition")
{
string a_1;
string a_2;
cout << "You chose addition. Press enter" << endl ;
cin.get();
cout << "Type in the first value: ";
getline( cin, a_1);
cout << "Type in the second value: ";
getline (cin, a_2);
cout << a_1 << " + " << a_2 << " = " << a_1 + a_2 << endl;
}
else
{
cout << "You spelled it wrong.";
return 0;
}
if ( c == "Subtraction")
{
string s_1;
string s_2;
cout << "You chose subtraction. Press enter" << endl ;
cin.get();
cout << "Type in the first value: ";
getline (cin, s_1);
cout << "Type in the second value: ";
getline (cin, s_2);
cout << s_1 << " - " << s_2 << " = " << s_1 - s_2 << endl;
}
}
I get this as the only error
42 83 C:\Users\Jason\Desktop\Lesson - Header Files\LH1.cpp [Error] no match for 'operator-' in 'first_argument - second_argument'
I don't get it. The addition sign works and everything but the subtraction works.
So I messed around with something else
cout << first_argument << " - " << second_argument << " = " << first_argument - second_argument << endl;
But that subtraction part works fine. I don't get it. Help please
string can deal with text. When you add two strings, they are concatenated ("2"+"2"=="22", not "4"). String doesn't have operator-.
To deal with floating-point numbers, use double. To deal with integers, use int:
double d1, d2;
//some output
cin >> d1;
//some output
cin >> d2;
cout << d1 << " - " << d2 << " = " << (d1-d2) << '\n';
The addition part works because string + string results in stringstring. It appends the two strings and returns a new string.
But subtracting two strings doesn't mean anything.
What I believe you actually want to do is convert the strings into numbers and then subtract the numbers.
To do that, you need to use something like the following:
double val_1, val_2;
cin >> val_1;
cin >> val_2;
cout << "result is " << (val_1 - val_2) << endl;
I put the subtraction inside parenthesis because I believe the << aka "shift" operator is on the same level as multiplication, which means that without them it would try to evaluate ("result is " << val_1) - (val_2 << endl).
Since I am not sure on operator precedence I checked http://en.cppreference.com/w/cpp/language/operator_precedence and found that << is lower than subtraction, so my parenthesis weren't necessary.
#include <iostream>
#include <string>
#include <limits>
using namespace std;
int main()
{
cout << "Hello there, this is your personal simple calculator.";
cin.get();
cout << "Type in what you want to do. (Addition, Subtraction, Multiplication, Division)" << endl;
string c;
getline(cin, c);
if (c == "Addition")
{
int a_1;
int a_2;
cout << "You chose addition. Press enter" << endl;
cin.get();
cout << "Type in the first value: ";
cin >> a_1;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Type in the second value: ";
cin >> a_2;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << a_1 << " + " << a_2 << " = " << a_1 + a_2 << endl;
}
else if (c == "Subtraction")
{
int s_1;
int s_2;
cout << "You chose subtraction. Press enter" << endl;
cin.get();
cout << "Type in the first value: ";
cin >> s_1;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Type in the second value: ";
cin >> s_2;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << s_1 << " - " << s_2 << " = " << s_1 - s_2 << endl;
}
else
{
cout << "You spelled it wrong.";
return 0;
}
}
Use if else statements because otherwise your code won't have a chance to check to see if the user is trying to Subtract. It is best to leave the else at the very end.
Also changed the strings to ints because strings cannot subtract as they are not numbers.
On a final note, I used the cin.clear() & cin.ignore() to flush the cin buffer.