C++ No instance of overloaded function getline matches argument list - c++

I'm writing a program which needs to read input from cin into a string. When I tried using the regular getline(cin, str) it endlessly prompted for input and never moved on the the next line of code. So I looked in my textbook and it said I could pass a cstring and size of the string to getline in the form of cin.getline(str, SIZE). However, when I do that I get the error "no instance of overloaded function getline matches the argument list.
I searched around, but all I found was people saying to use the getline(cin,str) form which led to the infinite input prompt, or the suggestion that there might be two different getline functions with different parameters in the classes I'm including, and that I need to tell the IDE to use the correct one(I'm not sure how to do that).
This is what I include at the beginning of my file:
#include <string>
#include <array>
#include <iostream>
#include "stdlib.h"
#include "Bank.h" //my own class
using namespace std;
And this is the relevant section of code:
const int SIZE = 30; //holds size of cName array
char* cName[SIZE]; //holds account name as a cstring (I originally used a string object in the getline(cin, strObj) format, so that wasn't the issue)
double balance; //holds account balance
cout << endl << "Enter an account number: ";
cin >> num; //(This prompt works correctly)
cout << endl << "Enter a name for the account: ";
cin.ignore(std::numeric_limits<std::streamsize>::max()); //clears cin's buffer so getline() does not get skipped (This also works correctly)
cin.getline(cName, SIZE); //name can be no more than 30 characters long (The error shows at the period between cin and getline)
I'm using Visual Studio C++ 2012, if that's relevant

This is the offending line:
char* cName[SIZE];
What you really need here is:
char cName[SIZE];
Then, you should be able to use:
cin.getline(cName, SIZE);

This error message from visual studio is quite misleading. Actually for me I was trying to call a non const member function from const member function.
class someClass {
public:
void LogError ( char *ptr ) {
ptr = "Some garbage";
}
void someFunction ( char *ptr ) const {
LogError ( ptr );
}
};
int main ()
{
someClass obj;
return 0;
}

Related to the answer of R Sahu the compiler gives a clue that the argument does not match.
Try the following code which does not give the error and makes the error message more clear.
#include <iostream>
class someClass {
public:
void LogError(char* ptr) {
std::cout << "LogError: before arg=" << ptr << "\n";
ptr[0] = 0;
std::cout << "LogError: after arg=" << ptr << "\n";
}
void LogError(char* ptr) const {
std::cout << "const LogError: arg=" << ptr << "\n";
}
void ROFunction(char* ptr) const {
LogError(ptr);
}
void RWFunction(char* ptr) {
LogError(ptr);
}
};
int main()
{
char s[] = "test";
someClass obj;
obj.ROFunction(s);
obj.RWFunction(s);
obj.ROFunction(s);
return 0;
}
With the output:
const LogError: arg=test
LogError: before arg=test
LogError: after arg=
const LogError: arg=

Related

Calling a string getter function from a header file

I'm learning C++, and I'm just messing around with putting classes in separate files for practice. I have a getter function, which returns a string (because the variable is saved as a string). However, from my main() function, I am not sure how to call it. I know the problem is probably that I need to include string somewhere when I call the object, but I have no idea how to format it.
I know this is a pretty newbie questions, but I couldn't find the answer anywhere. Could someone help me out?
(p.s. I'm not trying to get this specific code to work, since it's useless. I'm just trying to learn how to apply it for future reference).
I've tried throwing in string in a couple of places when calling or creating the object, but I always get an error. I know I could get around it by not encapsulating the variable or not having a separate class file, but that's not what I want.
main.cpp
#include <iostream>
#include "usernameclass.h"
#include <string>
using namespace std;
int main()
{
usernameclass usernameobject;
usernameobject.getUsername();
return 0;
}
usernameclass.h
#ifndef USERNAMECLASS_H
#define USERNAMECLASS_H
#include <string>
class usernameclass
{
public:
usernameclass();
std::string getUsername();
void setUsername(std::string name);
askUsername();
private:
std::string usernameVar = "test";
};
#endif
usernameclass.cpp
#include "usernameclass.h"
#include <iostream>
#include "username.h"
#include <string>
using namespace std;
string usernameclass::getUsername(){
return usernameVar;
cout << "test cout" << endl;
}
usernameclass::askUsername(){
string name;
cout << "What is your name?" << endl;
cin >> name;
setUsername(name);
cout << "Ah, so your name is "+usernameVar+", great name I guess!" << endl;
cin.get();
cin.get();
cout << "You're about to do some stuff, so get ready!" << endl;
}
usernameclass::usernameclass(){}
void usernameclass::setUsername(string name){
string* nameptr = &usernameVar;
*nameptr = name;
}
Expected result: runs getUsername() function and returns usernameVar
Actual result: doesn't run the getUsername() function
The current code would not compile, because you have not specified return type of 'askUsername()' routine, which is 'void', I believe.
Other things are good, apart from an output in 'getUsername()', which happens after returning from the function and about which you should have received a warning, I guess.
To the question: you can call that 'get' method in 'main()' as:
cout << usernameobject.getUsername();
Your code should be structured more like this instead:
main.cpp
#include <iostream>
#include "usernameclass.h"
int main()
{
usernameclass usernameobject;
// optional:
// usernameobject.askUsername();
// do something with usernameobject.getUsername() as needed...
return 0;
}
usernameclass.h
#ifndef USERNAMECLASS_H
#define USERNAMECLASS_H
#include <string>
class usernameclass
{
public:
std::string getUsername() const;
void setUsername(std::string name);
void askUsername();
private:
std::string usernameVar = "test";
};
#endif
usernameclass.cpp
#include <iostream>
#include "usernameclass.h"
std::string usernameclass::getUsername() const {
return usernameVar;
}
void usernameclass::setUsername(std::string name) {
usernameVar = name;
}
void usernameclass::askUsername() {
std::string name;
std::cout << "What is your name?" << std::endl;
std::getline(std::cin, std::name);
setUsername(name);
std::cout << "Ah, so your name is " << getUsername() << ", great name I guess!" << std::endl;
std::cout << "You're about to do some stuff, so get ready!" << std::endl;
}

how to read a const char* from keyboard input and perform strlen() on it?

So I have been trying for 1.30 hour to get this to work. I am new indeed, but I have searched all over the place and couldn't find an exact answer. I do not wish to do this another way, as it would take away the entire purpose of learning to code. I have to find why this thing isn't working. I tried dozens if not hunderds of syntaxes, but nothing works.
I want to read in a const char* name, than count the number of elements in it, so I thought had to be strlen(), and than output the name and the number of elements. If that works I can write the rest of the code.
#include <iostream>
using namespace std;
int main()
{
//writing your name, and counting the characters including \0
int a;
const char* name;
a = int strlen(name);
cin.getline(name);
cout << name;
cout >> a;
return 0;
}
There are a lot of problems with your code.
You are not allocating any memory for cin.getline() to read into. const char* name; is declaring an uninitialized pointer to nothing. You have to allocate memory for name before you can then read any data into it.
cin.getline() expects two input parameters (a pointer to an allocated buffer, and the max number of characters the buffer can hold), but you are only passing in one value.
You are calling strlen() before you have read anything into name (and there is a syntax error on your strlen() statement anyway).
You are passing a to std::cout using >>, but std::ostream does not implement the >> operator. You have to use << instead.
And lastly, don't use using namespace std;.
Try this instead:
#include <iostream>
#include <cstring>
int main()
{
//writing your name, and counting the characters including \0
int a;
char name[32];
std::cin.getline(name, 32);
a = std::strlen(name);
std::cout << "You entered: " << name << std::endl;
std::cout << "It is << a << " chars in length" << std::endl;
return 0;
}
Or, if you really don't like using std:: everywhere, at least use using <identifier>; instead of using namespace std;:
#include <iostream>
#include <cstring>
using std::cin;
using std::strlen;
using std::cout;
using std::endl;
int main()
{
//writing your name, and counting the characters including \0
int a;
char name[32];
cin.getline(name, 32);
a = strlen(name);
cout << "You entered: " << name << endl;
cout << "It is " << a << " chars in length" << endl;
return 0;
}
Now, that being said, the preferred solution is to use std::getline() instead of cin.getline():
#include <iostream>
#include <string>
int main()
{
int a;
std::string name;
std::getline(std::cin, name);
a = name.length();
std::cout << "You entered: " << name << std::endl;
std::cout << "It is " << a << " chars in length" << std::endl;
return 0;
}
I found a working solution, although I don't see where I had gone wrong. But this does exactly what I want using const char* and strlen() without using std::string.
Thanks for all your help, you have all pointed me to the correct direction.
#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
int main ()
{
const char *name;
int len;
name = "stephane";
len = strlen(name);
cout << name;
cout << len;
return(0);
}
As another user has pointed out, I think it's a good idea for you to take a few steps back and read the basics until you understand how pointers work.
A const char* is that: const. It could be used usually while doing things like this:
const char* cpName = "Stephane"; //expected not to change through the program's lifetime
char* pName = "Stephane"; //can be changed to point to something else
char *pOther = "Vada";
pName = pOther; //pName now points to the string "Vada"
cpName = pOther; //this won't compile as cpName is const

Passing values to arrays in a class (C++)

Trying to learn C++ and came across OOP. I don
t grasp how strncpy(m_strName, strName, 25); works. Isn't this a function? Where is it calling from? I see that it is calling m_strName by pointing through *strName, but how are the values being passed here?
source: program tutorial
#include <iostream>
class Employee
{
public:
char m_strName[25];
int m_nID;
double m_dWage;
// Set the employee information
void SetInfo(char *strName, int nID, double dWage)
{
strncpy(m_strName, strName, 25);
m_nID = nID;
m_dWage = dWage;
}
// Print employee information to the screen
void Print()
{
using namespace std;
cout << "Name: " << m_strName << " Id: " <<
m_nID << " Wage: $" << m_dWage << endl;
}
};
int main()
{
// Declare two employees
Employee cAlex;
cAlex.SetInfo("Alex", 1, 25.00);
Employee cJoe;
cJoe.SetInfo("Joe", 2, 22.25);
// Print out the employee information
cAlex.Print();
cJoe.Print();
return 0;
}
char * strncpy ( char * destination, const char * source, size_t num )
Copies the first num characters of source to destination. If the end of the source C string (which is signaled by a null-character) is found before num characters have been copied, destination is padded with zeros until a total of num characters have been written to it.
strncpy(m_strName, strName, 25); will copy 25 characters from strName to m_strName. This function resides in the cstring header file. You will have to include this file in order to use this function.
If you understand this, you will realise that most of your questions don't make sense.

C++ : Turn char array into a string that is printed

just a beginner student learning basic C++. I'm trying to figure out the best way to:
Turn a char array Name of 20 into a string that can be printed.
I found in other Stack Overflow topics to use "str()" such as "str(Name)", but it always comes up 'identifier not found'.
cout << "Name:" << str(Name) << endl;
Set a char array of 20 characters. For some reason, the following gives me errors when declaring. I've tweaked it so many times, but I cannot get why it won't give.
TESCStudent.Name[20] = {'S','u','p','e','r','P','r','o','g','r','a','m','m','e','r','\0'};
Full code I have so far:
#include <iostream>
#include <conio.h>
#include <string>
using namespace std;
//Step 1
struct StudentRecord
{
char Name[20];
//Accessor
void printInfo() const;
};
void StudentRecord::printInfo() const
{
cout << "Name:" << str(Name) << endl;
}
int main()
{
//Step 2
StudentRecord TESCStudent;
TESCStudent.Name[20] = {'S','u','p','e','r','P','r','o','g','r','a','m','m','e','r','\0'};
//Step 3
TESCStudent.printInfo();
_getch();
return 0;
}
Given that you are at a very beginner level, just use std::string:
#include <iostream>
#include <conio.h>
#include <string>
struct StudentRecord {
std::string Name;
void printInfo() const {
std::cout << "Name:" << Name << '\n';
}
};
int main() {
StudentRecord TESCStudent;
TESCStudent.Name = "SuperProgrammer";
TESCStudent.printInfo();
_getch();
}
Live demo
The syntax like this:
char Name[20] = {'S','u','p','e','r','\0'};
is used to initialize a variable when you define it. However, in your case,
StudentRecord TESCStudent;
TESCStudent.Name[20] = ...;
You've already defined it on the line before, so you can't "initialize", you have to "assign" it.
This is pretty much why you use std:string instead of char[].

Unexpected result while passing struct to a function

I want to pass a struct to function something like below (I know i can pass single member to function like input(int age, string s) but i want to pass whole struct like input(student s) )
#include <iostream>
using namespace std;
struct student
{
string name;
int age;
};
void input(student s)
{
cout << "Enter Name: ";
cin >> s.name;
cout << "Enter age: ";
cin >> s.age;
}
int main(int argc, char *argv[]) {
struct student s1;
input(s1);
cout << "Name is: " << s1.name << endl;
cout << "Age is: " << s1.age << endl;
}
Above code does not produce correct output, I want to use above code with pointer so to get expected output.
Test:If i input name to "abc" and age to 10. It does not get printed in main
Your function makes a local copy of the input. It looks like you need to pass by reference:
void input(student& s) { .... }
// ^
By default, function arguments are passed by value, so this issue is not specific to classes. For example,
void increment_not(int i) { ++i; }
int i = 41;
increment_not(i);
std::cout << i << std::endl; // prints 41
Your function passes student s by value, that's why the variable s1 in main doesn't change.
Change it to pass reference:
void input(student& s)
// ^
You need to pass the struct by reference, rite now you are passing it by copy so whatever changes are made they are on copy of the passed object.
void input(student& s){....}