char ** ptr = new char *[3];
ptr[0] = new char [5];
ptr[1] = new char [6];
ptr[2] = new char [7];
cout<<"Enter first array: ";
cin.getline(ptr[0], 5);
cin.getline(ptr[1], 6);
cin.getline(ptr[2], 7);
for (int i=0; i<3; i++){
cout<<ptr+i<<endl;
}
for (int i=0; i<3; i++){
delete[] ptr[i];
}
When I run this code, it gives the following output:
Enter first array: name
0xf99c20
0xf99c28
0xf99c30
I actually wanted the user input printed out.
Could someone please tell me how to do this?
The type of ptr+i is char**, not char*, so is just being printed as a pointer. To have it print as a string, use ptr[i], which is a char*.
That said, use a std::vector<std::string>. Then you can use the string version of std::getline. Then you avoid many possible problems with matching up new and delete, leaks, dealing with longer user input, dealing with a different number of lines of user input, etc.
Also, please reconsider your use of what are often considered bad practices: using namespace std; and endl (those are links to explanations).
you have logic misunderstanding of pointer concept when you print ptr+i it will give you the actual address locations of your inputs in the memory
to print the value of pointer you can use:
*(ptr+i)
or :
ptr[i]
also getline (char* s, streamsize n ); max stream size of your inputs should be bigger because there is a null character '\0' at the end of each character sequences and newline character '\n' when you enter another input:
cin.getline(ptr[0], 10);
cin.getline(ptr[1], 10);
cin.getline(ptr[2], 10);
link to the solution:
https://ideone.com/maSOSs
Related
char* name[4];
int j=0;
while(cin.getline(name[j],80))//input given:you(ent)me(ent)he(ent)she
cout<<name[j++];
this code is reading only one string upto one newline.should'nt it read all 4 strings and print them ?and is this a good way to input string using getline?
Problem: You are not allocating the memory properly. You are declaring an array of pointers not an array of c style strings.
Possible Solutions: You need to read about pointers and memory allocation first. You can either allocate memory first to each of the four pointers that you declared name[0], name[1], name[2], and name[3] using the following code:
char* name[4];
for (int i = 0; i < 4; i++)
{
name[i] = new char[80];
}
OR you can use a 2D array for which the code is posted below:
char name[4][80];
int j=0;
while(j<4 && cin.getline(name[j],80))
{
cout<<name[j++];
}
I made a bit of correction. And it works on my computer.
char* name[4];
for (int i = 0; i < 4; i++)
name[i] = new char[80];
int j = 0;
while (j < 4)
{
cin.getline(name[j], 80); //input given:you(ent)me(ent)he(ent)she
cout << name[j++] << endl;
}
You need to read some more about pointers, arrays and memory management in C++ i guess. You try to operate on C array of strings, but you didn't initialize it properly. You need to allocate memory before you use such pointers. Currently your program results in UB so you are actually really lucky that it did anything same at all.
Another issue is that, when you reach the end of your input, when j=4, you will still attempt to perform cin(getline(name[j], 80) but you are passing the name[4] as a parameter, which may be a cause of another UB, even if you allocate the memory correctly beforehand.
Other then that you are writing in C++, so use C++ string and vector instead of C arrays.
This is easily done with strings and std::getline:
#include <iostream>
#include <vector>
using namespace std;
int main(){
vector<string> names;
string name;
while(getline(cin, name)){
names.push_back(name);
cout<<name<<endl;
}
return 0;
}
so here's the thing I've been working on a code for 5 hours now and logic looks good the program seems to do it's job, the only thing that keeps bugging me is dynamic memory allocation of strings. The question does not specify the initial number of strings user has to enter. Here's what I've been trying to do to dynamically take the strings :
int t;
cin>>t //number of strings user wishes enter
char *s1[1000009]; //1000009 is the maximum number of digits each string can have
for(i=0;i<t;i++)
{
s1[i]=(char *)malloc(1000009)
cin>>s1[i];
}
not sure if it is the right way or not. A way through which i could store a 2D character array would also do if not dynamic strings.
Thanking you,
gaurav
Use a vector of strings instead of using malloc/new.
int t;
std::cin >> t;
std::vector<std::string> strings(t); //Create t strings
for(int i = 0; i < t; i++)
std::cin >> strings[i]; //Read into each string
Since you tagged this question as C++ I would do it like this:
std::vector<std::string> s1(1000009);
That's all - no need to use malloc, no need to take care about destruction.
If you are using C++ use the Tools you have available.
i would do it like this :
int i = 0;
char **s1;
s1 = (char **)malloc(t * sizeof(char *));
while (i < t)
{
s1[i] = (char *)malloc(1000009 * sizeof(char));
i++;
}
the first malloc create you t line.
The second one fill alloc 100000009charactere for each lines
I have a string that contains what ever the user has input
string userstr = "";
cout << "Please enter a string ";
getline (cin, userstr);
The string is then stored in userstr, I then want the string to be stored in a integer array where each character is a different element in the array. I have created a dynamic array as the following:
int* myarray = new int[sizeof(userstr)];
However how do I then get my string into that array?
You can access each element in your string using the [] operator, which will return a reference to a char. You can then deduct the int value for char '0' and you will get the correct int representation.
for(int i=0;i<userstr.length();i++){
myarray[i] = userstr[i] - '0';
}
int* myarray = new int[ userstr.size() ];
std::copy( usestr.begin(), userstr.end(), myarray );
The terminating zero was not appended to the array. If you need it you should allocate the array having one more element and place the terminating zero yourself.
You can just simply use isstringstream to convert the string to int as follows
istringstream istringName(intString);
istringName >> real_int_val;
now it has magically become a int containing all numbers from string
However I do not see why you would not cin it as a int in the first place??
Here is one way to do it
for(int i=0;i<userstr.length();i++){
myarray[i] = userstr[i];
}
I am new to C++ but have many years of programming. All my learning has been very good until I reached pointers. I must admit am struggling to accomplish simple stuff. For example, after failing to store array data into pointers - and then list the pointers, I went basic with below to help me understand. In this, I am aiming to enter a list of names into array pointer (or something like that), then retrieve the list the values from the memory location.
a) I am not able to put this to allow request input and store to pointer
b) when I loop through a pointer, it only displays the first characters of the names. If someone can help me achieve the above, it will be my BIGGEST breakthrough in pointers.
please help;
CODE
#include "stdafx.h"
#include<iostream>
#include<cstring>
#include<cctype>
using namespace std;
int i=0;
int main(){
char* studentNames[6]={"John Xyy","Hellon Zzz","Wendy Mx","Beth Clerk", "Jane Johnson", "James Kik"};
int iloop = 0;
//loop through and list the Names
for(iloop=0;iloop<6;iloop++){
cout<<"Student :"<<studentNames[iloop]<<" Addr:"<<&studentNames[iloop]<<endl;
}
cout<<endl;
system("pause");
//Now try and list values stored at pointer memory location
int p=0;
for (p=0;p<6;p++){
cout<<*studentNames[p];
}
cout<<endl;
system("pause");
return(0);
}
a) I am not able to put this to allow request input and store to pointer
Use fgets() to read strings from stdin as follows. You have array of size 6 pointers to characters. Assuming the strings length to 100 characters each, for each string read from stdin allocate buffer memory and copy it to studentNames array of pointers everytime.
char *studentNames[6];
char input[100];
for (int str = 0; str < 6; str++) {
if (fgets(input, sizeof(input), stdin) != NULL) {
studentNames[str] = (char *)malloc(strlen(input));
strcpy(studentNames[str], input);
}
}
b) when I loop through a pointer, it only displays the first characters of the names.
//Now try and list values stored at pointer memory location
int p = 0;
for (p = 0; p < 6; p++){
cout<<*studentNames[p];
}
In the above string printing, *studentNames[p] dereferences pth array of pointer each time in loop which prints first character only. Replace it with studentNames[p] which prints string literals.
I'm a beginner and i need to ask a question..
I wrote this small code that accepts a string from the user and prints it..very simple.
#include <iostream>
using namespace std;
int main()
{
int i;
char *p = new char[1];
for(i = 0 ; *(p+i) ; i++)
*(p+i) = getchar();
*(p+i) = 0;
for(i = 0 ; *(p+i) ; i++)
putchar(*(p+i));
return 0;
}
when i enter any string..like "stack overflow" for example..it will print "sta" and drop the rest of the string. I know it's an easy one to solve but since I've just started i can't understand what's wrong here . Thanks in advance .
There are several problems with this code. First, you have a buffer overflow, because char *p = new char[1] allocates only one character for storage. This is exceeded when i > 0. Next, your first loop will keep going until it reaches a point in unallocated memory (undefined behavior) that has a value of zero. This just happens to be after the third value in your case. You probably wanted something more like *(p+i-1) == 0 to give "the last character read meets some condition." Finally, you're allocating memory with new[] and not properly deallocating it with a matching delete[].
Consider using std::cin and std::string for much safer and correct code:
#include <iostream>
#include <string>
int main(int, char**) {
std::string s;
std::cout << "Enter a string: ";
std::cin >> s;
std::cout << s << std::endl;
}
Here is some code along your lines that seems to work. I'm sure there are better (and more C++-ish) ways to do this...
#include <iostream>
using namespace std;
#define MAXLEN 80
int main()
{
int i=0;
char c;
char *p = new char[MAXLEN + 1]; // 1 char will not be sufficient
do // Doing this with a for loop would be unreadable
{
c = getchar();
*(p+i) = c;
i++;
} while( c != '\n' && i < MAXLEN ); // Check for a newline. How do you enter the zero with a keyboard?
*(p+i) = 0; // Ensure that the last character is zero
for(i = 0 ; *(p+i) ; i++) putchar(*(p+i)); // This is OK but difficult to read
delete [] p; // Don't forget this
return 0;
}
The fact that your program does anything is just luck; what stops *(p+i) from being \0 to begin with? It's weird that you're using getchar() and putchar() in a C++ program, too. What's the story behind this program?
If you read into memory, be sure that you allocate enough. new char[1] creates an array of only one char, but you are reading more then that. A simple temporary fix would be to simply allocate more, say new char[255].
Other notes:
you never delete the memory you allocated: delete[] p;
you should check wether you read as much characters as your buffer can hold: for(..;.. && i<bufferSize;..)
the condition in the first loop always checks the next character, not what you just read
*(p+i) is equivalent to p[i], which is more readable
why read and write only one character at a time?
why not use iostreams (std::in, std::out) and std::string as you are using C++?
you only allocate space for one character but you try to put many chars in it.
Is this homework? if so please tag it as such. Are you allowed to use STL?
If so then use std::vector instead on new char[1];
EDIT:to do it without any fiddly bits or STL
const int MAX = 100;
char *p=new char[MAX];
for(i = 0 ; *(p+i) && i < MAX ; i++)
*(p+i) = getchar();
probably some out by ones - left as exercise