Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I'm starting out on how to code in c++.
I've been reading c++ primer plus (5th edition) book and came across an example program which I don't fully understand. Basically, the program asks for your last name and gives you the address of where it gets stored:
#include <iostream>
#include <cstring>
using namespace std;
char* getname();
int main();
{
char* name;
name = getname();
cout << name << " at " << (int*)name << endl;
delete [] name;
name = getname();
cout << name << " at " << (int*)name << endl;
delete [] name;
return 0;
}
char* getname()
{
char temp[80];
cout << "Enter last name: ";
cin >> temp;
char* pn = new char [strlen(temp)+1];
strcpy(pn, temp);
return pn;
}
I don't quite get why char* getname() function needs the dereference operator. I'm having a little bit of trouble understanding this program overall, hehe.
Sorry if this comes across like a silly question, but I'm quite stuck. That's all. Thank you!..
name - it's a pointer to first char in sequence.
std::cout with << - has different behavior depending on what you give him.
If its pointer to first char in sequence (char* name) - cout printing this sequence.
If its pointer to int number - cout printing address of this number in memory (0x1105010)
(int*) - casting to pointer to int.
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 months ago.
Improve this question
Hi everyone I have a simple task in C++:
-> writing a program that takes a string from user input and loops over the characters in the string via a pointer.
If I understand correctly, then a previously declared string name; variable can also be accessed via const char*, implying that I can declare a pointer in the following manner: const char *pName = &(name[0]);. When printing the pointer, however, not the memory address but the actual variable is displayed in the terminal (see my code below). This prevents me from incrementing the pointer (see for loop).
Filename: countchar.cpp
#include <iostream>
using namespace std;
int main() {
string name;
std::cout << "Provide a string." << endl;
std::cin >> name;
const char *pName = &(name[0]);
cout << pName << endl;
// further downstram implementation
// int len = name.length();
// for(int ii = 0; ii < len; ii++){
// std::cout << "iteration" << ii << "address" << pName << endl;
// std::cout << "Character:" << *pName << endl;
// (pName+1);
// }
return 0;
}
Terminal output:
$ g++ countchar.cpp -o count
$ ./count
$ Provide a string.
$ Test
$ Test
As I am a quite a noob in regard to C++ help and an explanation are both highly appreciated (No material found online that solves my problem). Thanks in advance!
The operator << overloaded for a pointer of the type char * such a way that it outputs the string pointed to by the pointer.
So according to the assignment instead of these statements
const char *pName = &(name[0]);
cout << pName << endl;
you need to use a loop like
for ( const char *pName = &name[0]; *pName != '\0'; ++pName )
{
std::cout << *pName;
}
std::cout << '\n';
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 12 months ago.
Improve this question
#include <bits/stdc++.h>
using namespace std;
int main()
{
char *str;
gets(str);
int size = strlen(*(&str));
//How to iterate through this str which is acting like a string here
return 0;
}
//I'm trying to print each char in a new line.
Ignoring all the other problems, such as using an uninitialized pointer, using gets (it's so bad it's been removed from C and C++), including bits/stdc++.h, not using std::string and std::getline...
Using your size variable, you can use loop like this:
for(int index = 0 ; index < size ; ++index) {
std::cout << "character at index " << index << " is '" << str[index] << "'\n";
}
But note that your code will crash at gets and never get to this loop. Please find better learning material to get started with C++!
PS. To get your code to not crash, change char *str; to char str[10000];... Then that program should run and you are unlikely to accidentally cause a buffer overflow. Still, I repeat, get better learning material!
The character pointer str doesn't point to any char object and has not been initialized.
Second, the function gets has been deprecated in C++11 and removed in C++14.
A better way would be to use std::string instead as shown below:
#include <string>
#include <iostream>
int main()
{
std::string str;
//take input from user
std::getline(std::cin, str);
//print out the size of the input string
std::cout << str.size() << std::endl;
//iterate through the input string
for(char& element: str)
{
std::cout<<element<<std::endl;
}
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I know how to use a string to calculate the number of characters, but I'm not sure how to use a function to do that. have to use CSTRING. THANK YOU ALL
#include <cstring>
char a[10];
cout << "Please enter anything: ";
cin.getline(a,10);
cout << "You type " << strlen(a) << " letters long"<<endl;
You're probably looking for std::string since you're question mentioned C++ and not only C.
include <string>
std::string myString = "Something";
size_t stringLength = myString.size();
It's simple. Just type your code inside a function()
int stringlengthfunction()
{
char str[80];
int i;
cout<<"\n enter string:";
cin.getline(str,80);
int n=strlen(str);
cout<<"\n lenght is:"<<n;
getch();
return 0;
}
or pass your string as a parameter to the function
int stringlengthfunction(string str)
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
This is the professor's code:
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
#include<string>
#include <new>
int main()
{
char *p;
int index = 8;
cout << "Input how many characters:";
cin >> index;
p = new char [index + 1];
cin >> p;
cout << "p is: " << p;
delete [] p;
p = NULL;
return 0;
}
After I ANSWER "how many characters" statement with a number the program stops.
Anyone knows why?
First you have
cin >> index;
where you have to input the number of characters.
Then you have
cin >> p;
where you have to input some characters - but no more than the number you gave before. Are you doing that? It might be helpful to give another prompt:
cout << "Input up to " << index << " characters:";
cin >> p;
I hope your professor is going to follow this up with an explanation of buffer overruns, input validation, exception safety, and how to use std::string to avoid faffing around with manual allocation. Otherwise, you're being taught some very bad habits.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I went through similar question on stackoverflow but it did not solve my issue
I am trying to send string array as below
void manipulateString( char *);
int hashTable (int &, char * );
const int HTsize = 10;
int main()
{
const int size = 100;
char inputString[size];
cout << " Enter first names ( separate by a space ) \n ";
cin.getline(inputString,size);
manipulateString(inputString);
return 0;
}
void manipulateString (char *input)
{
int firstNamelen;
int hIndex=0,newIndex=0;
int totalName = 0;
char *firstname;
firstname = strtok(input, " "); // separate firstname
while (firstname != NULL)
{
firstNamelen = strlen(firstname);
hIndex = hashfunction(firstname,firstNamelen);
newIndex=hashTable(hIndex, firstname);
cout << "\n\n ( " << firstname << " ) is stored at index [" << hIndex << "] of hash table " << endl;
firstname = strtok(NULL, " " ); // next first name
}
}
When it reaches to void manipulateString (char *input) it gives segmentation fault. what is the issue?
Given that hashfunction and hashTable are not leading to a segmentation fault...
You can only read size-1 characters.
Check cin.fail() to see whether cin.getline was successfull. If not the string might not be NULL terminated. If the string is not NULL terminated, strlen or strtok might lead to a segmentation fault.