i'm working on a program that uses a function and pointers to replace commas with spaces after a user inputs a sentence.
However when I run the program I receive the above error and another that says;
"C++ a value of type "const char *" cannot be used to initialize an entity of type "std::string *""
having trouble with this program and wondering if anyone here can give me a nudge in the right direction?
Thank you!
Heres the code:
#include "stdafx.h"
#include <iostream>
#include <string>
#include <stdio.h>
using namespace std;
void comma2blank(string* pString1);
int main()
{
string* String1 = " " ;
cout << "Tell me why you like programming" << endl;
getline(cin, *String1);
comma2blank(String1);
cout << " String 1 without comma is: " << *String1 << endl;
delete String1;
system("pause");
};
void comma2blank(string* pString1)
{
pString1->replace(pString1->find(','), 1, 1, ' ');
pString1->replace(pString1->find(','), 1, 1, ' ');
};
You don't need to create a string pointer in your main(). You need a full string object and you can pass its address (a pointer) to your function like this:
int main()
{
string String1; // NOT a pointer!
cout << "Tell me why you like programming" << endl;
getline(cin, String1);
comma2blank(&String1); // NOTE: pass by pointer using & (address of)
cout << " String 1 without comma is: " << String1 << endl;
// no need to delete anything here
system("pause");
};
Related
The code below fails on gcc 9.4.0. Is this just a bug, or have I done something stupid?
log declares an ostringstream object, writes a filename and a line number to it, and attempts to do something with the object's underlying str().c_str().
Valgrind shows this crashing at the pointer access. The output I get is:
foo.cc, line 100
cptr is at 0x55c45e8f00c0, and is
#include <iostream>
#include <sstream>
#include <cstdarg>
using std::cout;
using std::ostringstream;
void log(const char *fname, int lineno) {
ostringstream outstr;
outstr << fname << ", line " << lineno;
cout << outstr.str() << '\n'; // prints Ok
const char *cptr = outstr.str().c_str();
cout << "cptr is at " << (void*) cptr << ", and is " << cptr; // crash
}
int main() {
log("foo.cc", 100);
}
std::ostringstream::str() returns a temporary string which will be destructed at the end of the line, this then means cptr is a dangling pointer.
Try:
std::string str = outstr.str();
const char *cptr = str.c_str();
cout << "cptr is at " << (void*) cptr << ", and is " << cptr;
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
I'm struggling with this C++ compiler error to get my regex_match() function to work. The code:
#include <iostream>
#include <string>
#include <regex>
using namespace std;
struct Person {
Person(string name, int age)
: n{name}, a{age}
{
regex r("^([!:*&%##^\\[\\]\"\'])+"); // :*[]"'&^%##!
for(char test : n) {
cout << "Character: " << test;
if(regex_match(test, r)) {
cout << endl << "Error: wrong character!" << endl;
}
}
}
string n;
int a;
};
int main() {
Person Goofy("Goofy",11);
return 0;
}
I want to check if n contains at least one of the characters I wrote in the regex r().
Btw, for people learning regex I've found the great website: https://regex101.com.
Any sugestions? Thx!!
test is a character. There's no overload of std::regex_match for a character.
I'm not sure if you want to check every character against the list of characters or just the first one. If it's them all, you can use std::any_of:
char const constexpr m[] = R"(:*[]"'&^%##!)";
for(char test : n) {
if(any_of(begin(m), end(m), [test](char c){ return c == test; })) {
cout << endl << "Error: wrong character!" << endl;
}
}
Based on the additional comments I think I understand what you wanted: check if the string n contained any of the "illegal" characters. For this task std::regex_search is better suited:
regex r{R"([:*\[\]"'&^%##!])"};
if(regex_search(n, r)){
cout << endl << "Error: wrong character!" << endl;
}
My program worked like it was supposed to until I added the toupper part into my program. I've tried looking at my error code but it's not really helping. The errors are:
no matching function to call
2 arguments expected, one provided
So I know the error is in those two statements in my while loop. What did I do wrong?
I want to make a name like
john brown
go to
John Brown
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
using namespace std;
int main(){
string firstname[5];
string lastname[5];
ifstream fin( "data_names.txt" );
if (!fin) {
cout << "There is no file" << endl;
}
int i = 0;
while( i < 5 && (fin >> firstname[i]) && (fin >> lastname[i]) ) {
firstname[0] = toupper(firstname[0]);
lastname[0] = toupper(lastname[0]);
i++;
}
cout << firstname[0] << " " << lastname [0] << endl;
cout << firstname[1] << " " << lastname [1] << endl;
cout << firstname[2] << " " << lastname [2] << endl;
cout << firstname[3] << " " << lastname [3] << endl;
cout << firstname[4] << " " << lastname [4] << endl;
return 0;
}
std::toupper works on individual characters, but you are trying to apply it to strings. Besides adding #include <cctype>, you need to modify your while loop's body:
firstname[i][0] = toupper(firstname[i][0]);
lastname[i][0] = toupper(lastname[i][0]);
i++;
Then it should work as expected. Live demo here
As M.M helpfully pointed out in the comments, you should also check that your strings aren't empty before accessing their first characters, i.e. something like
if (!firstname[i].empty()) firstname[i][0] = toupper(...);
is strongly recommended.
Mind you, you will probably need more sophisticated logic if you get names like McDonald :)
You need ctype.h to get the proper definition for toupper(). It is usually implemented not as a function, but an array mapping.
#include <ctype.h>
The program has several flaws: using a string array instead of a string, not iterating through the string correctly, not declaring but using the C definition of toupper(), not exiting when the file does not exist.
Use this instead:
#include <ctype.h>
#include <iostream>
#include <string>
using namespace std;
int main ()
{
ifstream fin ("data_names.txt");
if (!fin)
{
cerr << "File missing" << endl;
return 1;
}
// not sure if you were trying to process 5 lines or five words per line
// but this will process the entire file
while (!fin.eof())
{
string s;
fin >> s;
for (i = 0; i < s.length(); ++i)
s [i] = toupper (s [i]);
cout << s << endl;
}
return 0;
}
I am suppose to write a program that will read from a text file and store what is inside the text file using structures and regroup and print out the information in the text file. But I have encountered problems with getline. I have try to write getline like this
getline(infile, info.name)
but it doesn't work. I have also include <string> and <cstring> but I still encounter errors like
error C2664: 'std::basic_istream<_Elem,_Traits>
&std::basic_istream<_Elem,_Traits>::getline(_Elem *,std::streamsize)'
: cannot convert parameter 1 from 'int' to 'char *'
and
error C2664: 'std::basic_istream<_Elem,_Traits> &std::basic_istream<_Elem,_Traits>::getline(_Elem
*,std::streamsize,_Elem)' : cannot convert parameter 1 from 'char [10][80]' to 'char *'
The text file that I am suppose to print out is the below text
Isabella Chan Republic of Singapore Libra 23 - 10 -
1993 7 I wish to be good in c++ I wish that
christina grimmie will win the voice I wish that ......
Sorry for the noob question and thanks in advance!
#include <iomanip>
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cctype>
#include <fstream>
#include <string>
using namespace std;
const int MAX = 80;
const int MAXNO = 10;
enum Zodiac
{
Aquarius, Pisces, Aries, Taurus,
Gemini, Cancer, Leo, Virgo,
Libra, Scorpio, Sagittarius, Capricorn
};
struct Date
{
Zodiac sign;
int day;
int month;
int year;
};
struct Student
{
char name [MAX];
char nationality [MAX];
Date birthDate;
int no; // no of other messages
char wishMessage [MAXNO][MAX];
// Feel free to add in more features
};
void myInfo (fstream&, char [], Student&);
// The above function reads information from the text file
// and store the information in a structure reference parameter
void printOut(Student);
int main()
{
fstream infile;
char fName[MAX];
Student info;
cout << "Enter your info file name: "
cin >> fName;
cout << endl;
myInfo(infile, fName, info);
printOut(info);
}
void myInfo (fstream& infile, char fName[], Student& info)
{
infile.open(fName, ios::in);
if(!infile)
{
cout << "Error file not found!" << endl;
exit(0);
}
infile.getline(info.name, MAX);
infile.getline(info.nationality,MAX);
infile << info.birthDate.sign
<< info.birthDate.day
<< info.birthDate.month
<< info.birthDate.year;
infile.getline(info.no, MAX);
infile.getline(info.wishMessage, MAXNO, MAX);
infile.close();
cout << "Successfully readed!" << endl;
}
void printOut(Student info)
{
cout << "My name is " << info.name << endl;
cout << "My nationality is " << info.nationality << endl;
cout << "My date of birth is " << info.birthDate.day
<< " " << info.birthDate.month << " "
<< info.birthDate.year << endl;
cout << "I am " << info.birthDate.sign << endl;
cout << "\n I have " << info.no << " wishes:" << endl;
}
It seems that you are trying to read into non-strings with getline, whereas it is reading into strings as per documentation.
Extracts characters from the stream as unformatted input and stores them into s as a c-string, until either the extracted character is the delimiting character, or n characters have been written to s (including the terminating null character).
Here are two offending lines:
infile.getline(info.no, MAX);
and
infile.getline(info.wishMessage, MAXNO, MAX);
The former is reading into int, the latter is into a string array.
You will need to first read the strings in, and then make the corresponding conversion operations as desired.