简体   繁体   中英

Not able to input strings using getline() .It is reading only one string

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM