2
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?

mbhatti_20
  • 45
  • 9

3 Answers3

4

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++];
}
Itban Saeed
  • 1,660
  • 5
  • 25
  • 38
1

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;
}
Tiefan Ju
  • 510
  • 3
  • 14
1

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;
}
K. Kirsz
  • 1,384
  • 10
  • 11
  • can u suggest some sources to strengthen this area of c++ @kirsz – mbhatti_20 Jul 23 '17 at 08:32
  • It is not a good idea to use both the singular and plural as a name of a variable. It is very easy to make mistakes. Perhaps `list_of_names`? – Ed Heal Jul 23 '17 at 09:21
  • Also please read https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice – Ed Heal Jul 23 '17 at 09:29