Why is this string operation not working? - c++

Here is the code:
#include <cmath>
#include <iostream>
using namespace std;
int main()
{
string sidelength;
cout << "Perimeter of Square" << endl;
cout << "Enter length of one side: ";
getline(cin, sidelength);
cout << sidelength * 4 << endl;
return 0;
}
When run, this is the error message:
error: no match for 'operator*' (operand types are 'std::__cxx11::string {aka std::__cxx11::basic_string<char>}' and 'int')|
How do I fix this error and make the program run correctly?

The get line function takes a string as it's second parameter, but you want to get an integer/double/float as an input. So don't use getline. Simply run this code below and it will solve your problem.
#include <cmath>
#include <iostream>
using namespace std;
int main()
{
int sidelength;
cout << "Perimeter of Square" << endl;
cout << "Enter length of one side: ";
cin >> sidelength;
cout << sidelength * 4 << endl;
return 0;
}

If you really want to multiply a string by a number, you can overload operator*:
#include <cmath>
#include <iostream>
#include <cctype>
#include <string>
std::string operator*(const std::string &s,int x) {
std::string result;
try {
result = std::to_string(stoi(s)*x);
} catch(const std::invalid_argument&) {
result="UND";
}
return result;
}
std::string operator*(const std::string &s,double x) {
std::string result;
try {
result = std::to_string(stof(s)*x);
} catch(const std::invalid_argument&) {
result="UND";
}
return result;
}
int main()
{
std::string input("1");
input = input * 5.32;
std::cout << input << std::endl;
input = input * 2;
std::cout << input << std::endl;
return 0;
}

Related

How to declare function using reference?

I am making this program to check the alphabetic and numeric characters of a C-type string. I am using C-type strings because it is for an assignment, otherwise I would opt to use std::string.
How do I declare the function? In my case, I want str, SAlpha and SNum, to be stored in the function as s, alpha, num. That's why I am using references, but I don't understand how to declare it without giving me an error saying undefined.
I have been searching, but I am new to functions, and don't understand them quite well. That's why I'm asking.
Below is the code:
#include <iostream>
#include <cstring>
#include <cctype>
using namespace std;
void seperate(char (&s)[], char (&alpha)[], char (&num)[]);
int main() {
char str[100];
char SAlpha[100];
char SNum[100];
cout << "Insert a string: ";
cin.getline(str,100);
strcpy(SAlpha, str);
strcpy(SNum,str);
cout << "Alphabetic characters " << endl;
for (int i = 0; i < strlen(SAlpha); i++) {
if (isalpha(SAlpha[i])) {
cout << " " << SAlpha[i];
}
}
cout << endl;
cout << "Numeric characters " << endl;
for (int i = 0; i < strlen(SNum);i++) {
if (isdigit(SNum[i])) {
cout << " " << SNum[i];
}
}
seperate(str, SAlpha, SNum); //UNDEFINED FUNCTION
return 0;
}
You are getting an "undefined" error because you have only declared the seperate() function but have not implemented it yet, eg:
#include <iostream>
#include <cstring>
#include <cctype>
using namespace std;
// THIS IS JUST A DECLARATION!!!
void seperate(char (&s)[100], char (&alpha)[100], char (&num)[100]);
int main() {
char str[100];
char SAlpha[100];
char SNum[100];
cout << "Insert a string: ";
cin.getline(str,100);
strcpy(SAlpha, str);
strcpy(SNum,str);
cout << "Alphabetic characters " << endl;
for (int i = 0; i < strlen(SAlpha); i++) {
if (isalpha(SAlpha[i])) {
cout << " " << SAlpha[i];
}
}
cout << endl;
cout << "Numeric characters " << endl;
for (int i = 0; i < strlen(SNum);i++) {
if (isdigit(SNum[i])) {
cout << " " << SNum[i];
}
}
seperate(str, SAlpha, SNum); // <-- OK TO CALL SINCE THE FUNCTION IS DECLARED ABOVE...
return 0;
}
// ADD THIS DEFINITION!!!
void seperate(char (&s)[100], char (&alpha)[100], char (&num)[100])
{
// do something here...
}

Loop and object intialization question (C++)

I'm trying to use a loop to infinitely create objects from a class unless a specific input is entered. I think I have everything done except the loop. I know how to initialize one object in my main function, but I'm stuck as to how to use a loop to do this infinitely. My code is below.
Driver File:
#include <iostream>
#include "square.h"
using namespace std;
int main()
{
square square1;
square1.setSide();
square1.calcArea();
square1.calcPerimeter();
square1.showData();
}
Header file:
#pragma once
#include <string>
class square
{
public:
square();
void setSide();
double getSide() const;
void calcPerimeter();
void calcArea();
void showData();
private:
double squareSide;
double squarePerimeter;
double squareArea;
};
Implementation file:
#include <iostream>
#include <iomanip>
#include "square.h"
square::square()
{
squareSide = 0;
squarePerimeter = 0;
squareArea = 0;
}
void square::setSide()
{
std::cout << "Enter a side length: ";
std::cin >> squareSide;
std::cout << "\n";
if (squareSide == -1)
{
std::cout << "Exiting program.\n";
exit(-1);
}
while (std::cin.fail() || squareSide < 0)
{
std::cout << "\nYou must enter a positive number. Please try again.\n\n";
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << "Enter a side length: ";
std::cin >> squareSide;
}
}
double square::getSide() const
{
return squareSide;
}
void square::calcPerimeter()
{
squarePerimeter = 4 * getSide();
}
void square::calcArea()
{
squareArea = getSide() * getSide();
}
void square::showData()
{
std::cout << "The side length of the square is: " << getSide() << "\n";
std::cout << "The perimeter of the square is: " << getSide() * 4 << "\n";
std::cout << "The area of the square is: " << getSide() * getSide() << "\n";
}
You could add a do ... while loop around your code in main and store the squares in a vector<square>.
Example:
#include <limits> // you use numeric_limits from this header
#include <utility> // move
#include <vector> // vector
int main() {
std::vector<square> squares;
std::string answer;
do {
square square1;
square1.setSide();
square1.calcArea();
square1.calcPerimeter();
// move the square into the vector
squares.push_back(std::move(square1));
// ask the user if he/she wants to enter another
std::cout << "Go again? ";
} while(std::cin >> answer && answer == "yes");
// display what you stored
std::cout << "You stored " << squares.size() << " square(s)\n";
for(square& sq : squares) {
sq.showData();
std::cout << '\n';
}
}

Read standard input and print standard output using function bool.getCharacter(char* c)

a. Read single character and print it to standard input.
b. Use the following function to the standard input. The function was bool.getCharacter(char* c).
Here's what I've done so far
#include <iostream>
#include <cstdio>
#define LENGTH 101
int main(void) {
#include <iostream>
using std::cin;
using std::cout;
int main() {
char c;
bool getCharacter(char* c) {
std::cout << &a << " " << a << std::endl;
while(std::cin >> *c) {
if(cin >> *c) {
cout << true << endl;
return 0;
}
else {
cout << false << endl;
return c;
}
return EXIT_SUCCESS;
}
error on line 11: a function-definition is not allowed here before ‘{’ token
Okay, I'm not going to solve all your problems, but let's start with this and see if you get further.
#include <iostream>
#include <cstdio>
#define LENGTH 101
using std::cin;
using std::cout;
bool getCharacter(char* c) {
std::cout << &a << " " << a << std::endl;
if (std::cin >> *c) {
return true;
}
return false;
}
int main(int, char **) {
char c;
while (getCharacter(&c)) {
cout << c << endl;
}
}
Basically, you tried nesting methods, which is really not allowed. And your getCharacter() method was doing way too much. It's supposed to get a character, not do anything else, and then you have to actually call it.

string hex to pointer get value

From the console i am asking for a hexadecimal string to convert to a pointer to reference an item in memory.
#include <iostream>
#include <sstream>
#include <Windows.h>
int char_to_pointer(std::string input);
int main() {
int sample = 100; // lets say this address is 0xc1f1
std::string input_;
std::cout << "addr:" << &sample << std::endl;
std::cout << "what is the memory address?:" << std::endl;
std::cin >> input_;
unsigned int inp = char_to_pointer(input_);
std::cout << "imp: " << inp << std::endl;
Sleep(10000);
return 0;
}
int char_to_pointer(std::string input) {
return std::stoul(input, nullptr, 16);
}
My problem is that char_to_pointer only converts the hex string into a decimal.
this is what i want:
input: "0xc1f1"
output: 100
I found the solution:
#include <iostream>
#include <sstream>
#include <Windows.h>
#include <string>
int *char_to_pointer(std::string input);
int main() {
int sample = 100; // lets say this address is 0xc1f1
std::string input_;
std::cout << "addr:" << &sample << std::endl;
std::cout << "what is the memory address?:" << std::endl;
std::cin >> input_;
int *inp = char_to_pointer(input_);
std::cout << "imp: " << inp << std::endl;
std::cout << "imp*: " << *inp << std::endl;//This was my solution
std::cout << "imp&: " << &inp << std::endl;
Sleep(10000);
return 0;
}
int *char_to_pointer(std::string input) {
return (int *)std::stoul(input, nullptr, 16);
}

How do I use "<<" with my own struct?

I have following program to access sqlite database and to get the content of a table into a LIST CONTAINER.
All I want is to print the data which is in the list container.But I get this ERROR.
error: expected primary-expression before ‘<<’ token
The below file is DBAccess1.cpp
#include <iostream>
#include <sqlite3.h>
#include <list>
#include <iterator>
#include <algorithm>
#include <string>
#include <cstring>
#include <sstream>
#include "DBAccess1.h"
bool sqliteDB::GET_ALL_Site_Code(list<SiteCode>& Site_Code_list)
{
sqlite3 *db;
const char *sql;
sqlite3_stmt * stmt;
int rc = sqlite3_open("/DBsqlite3/empdbv3.db", &db);
sql = "SELECT * FROM SiteCode;";
rc = sqlite3_prepare_v2(db, sql, -1, &stmt, 0);
while(sqlite3_step(stmt)==SQLITE_ROW) {
int column = sqlite3_column_count(stmt);
for(int i = 0; i < column; i++)
{
int A = sqlite3_column_int(stmt, 0);
int B = sqlite3_column_int(stmt, 1);
SiteCode info;
info.siteID = A;
info.siteCode = B;
cout<<"Preparing to push data into List"<<endl;
Site_Code_list.push_back(info);
cout<<"Data was pushed successfully"<<endl;
}//FOR LOOP ENDS HERE
}// WHILE LOOP ENDS HERE
sqlite3_finalize(stmt);
sqlite3_close(db);
return true;
}
//=================================XX=============================//
void sqliteDB::printList()
{
int s = Site_Code_list.size();
cout << "The size of List is :" << s << endl;
for( list<SiteCode> :: iterator it = Site_Code_list.begin(); it != Site_Code_list.end(); it++)
cout << it* << " "; //The ERROR occurs here
}
Below is my DBAccess.h file:
#ifndef DBAccess1_HH
#define DBAccess1_HH
#include <iostream>
#include <sqlite3.h>
#include <list>
#include <iterator>
#include <algorithm>
#include <cstring>
#include <sstream>
#include <string>
using namespace std;
struct SiteCode
{
int siteID;
int siteCode;
};
class sqliteDB {
public:
list<SiteCode> Site_Code_list;
bool GET_ALL_Site_Code(list<SiteCode>& Site_Code_list);
void printList();
};
#endif
And below is my main.cpp from where I am calling the functions:
int main()
{
sqliteDB object1;
list<SiteCode> Site_Code_list;
object1.GET_ALL_Site_Code(Site_Code_list);
object1.printList();
cout << "\n\nAll the statement were executed properly\n\n";
return 0;
}
The Error I get is:
error: expected primary-expression before ‘<<’ token
cout << it* << " ";
You have two "errors" in your code. The first is the one that everyone else has pointed out. This
cout << it * << " ";
should be this
cout << *it << " ";
Which if course generates the second error
no match for ‘operator<<’ (operand types are ‘std::ostream
{aka std::basic_ostream<char>}’ and ‘SiteCode’)
std::cout << *it << " ";
Which is actually telling you exactly what the problem is. You are trying to output a SiteCode object onto the stream, but there is no << operator defined for a SiteCode object.
You need to add the following for your SiteCode struct.
ostream& operator<< (ostream &out, SiteCode &site)
{
out << "(" << site.siteID << "," << site.siteCode << ")";
return out;
}
Declare this in the header file, after the struct is defined, thus:
struct SiteCode
{
int siteID;
int siteCode;
};
inline ostream& operator<< (ostream &out, SiteCode &site)
{
out << "(" << site.siteID << "," << site.siteCode << ")";
return out;
}
And now you will be able to use << with any SiteCode object on any stream.
How you actually format the output of the object is up to you. I just chose to display it as a tuple.
Introduction
Dereferencing an iterator is done with *it, not it* - the latter would expect another operand; "multiplication of it and primary-expression".
cout << *it << " "; // fixed
Note
The previous "fix" will require you to define a operator<< suitable for std::cout, and an object of type SiteCode.
If you just want to print the list in a simple manner you can do the following:
cout << it->siteID << " " << it->siteCode << "\n";