-1
#include <iostream>
#include<fstream>
using namespace std;

int main()
{
    int a;
    cout<<"enter key ";
    cin>>a;
    if(a==1)
    {
        string info[0][1];
        cout<<"enter your name ";
        getline(cin, info[0][0]);

        cout<<"enter father's ";
        getline(cin, info[0][1]);

        ofstream file("info.txt");
        for(int i=0;i<=1;i++)
        {
            file<<info[0][i]<<"   ";
        }

        file.close();
    }
    int b;
    cout<<"enter b ";
    cin>>b;
    if(b==2)
    {
        char info[0][1];
        ifstream file("info.txt");
        for(int j=0;j<=1;j++)
        {
            file>>info[0][j];
        }
        cout<<endl;
        for(int i=0;i<=4;i++)
       {
           cout<<info[0][i]<<"    ";
       }

    }
    return 0;
}

I want to store user and his father's name (other info as well which is not mentioned in code) in the form of 2d array, and ofstream that array and later ifstream the same.

in the code:

After taking input a=1, it displays "enter your name", to which it is not taking any input i.e nothing gets typed in the output window from keyboard. (no compiler error) Please help!!

I am coding in code blocks.

  • `string info[0][1];` - You probably confused indices and array sizes here. An array of size 0 is seldom useful (and shouldn't compile). Same for `char info[0][1];`. – churill Dec 18 '20 at 07:46
  • The issue you observe is explained in this question: [Why does std::getline() skip input after a formatted extraction?](https://stackoverflow.com/questions/21567291/why-does-stdgetline-skip-input-after-a-formatted-extraction), but there are more problems (like array of length 0 as noted above). – Yksisarvinen Dec 18 '20 at 07:48

1 Answers1

1

This is not legal C++ (because arrays of size zero are not legal).

    string info[0][1];
    cout<<"enter your name ";
    getline(cin, info[0][0]);

    cout<<"enter father's ";
    getline(cin, info[0][1]);

    ofstream file("info.txt");
    for(int i=0;i<=1;i++)
    {
        file<<info[0][i]<<"   ";
    }

All you need is two strings, so just

    string info[2];
    cout<<"enter your name ";
    getline(cin, info[0]);

    cout<<"enter father's ";
    getline(cin, info[1]);

    ofstream file("info.txt");
    for(int i=0;i<2;i++)
    {
        file<<info[i]<<"   ";
    }

Thne when you try to read them back, you've made the same error, and added a new one

    char info[0][1];

Why did you switch to char here? Again you need two strings.

    string info[2];

Finally for some reason at the end you are trying to output five strings.

   for(int i=0;i<=4;i++)
   {
       cout<<info[0][i]<<"    ";
   }

Again two is the magic number

   for(int i=0;i<2;i++)
   {
       cout<<info[i]<<"    ";
   }

Plus you have the problem mentioned by Yksisarvinen. You need to fix that in the way mentioned in the link.

john
  • 71,156
  • 4
  • 49
  • 68