-6

Why when I call function inside of the if statement the result is like:

please enter phone number: please enter your name:

But I need like:

please enter your phone number: 4545
please enter your name: dddf
#include <iostream>

using namespace std;

void insert_data ()
{
    string phone_number[10] = {};
    string name[10] = {};

    int count = 0;
    for(int i = 0; i < 10; i++ ){
        if(name[i] != "" ){
            count++;
        }
    }

    cout<< "please enter phone number: ";
    string new_phone_number;
    getline (cin, new_phone_number);
    phone_number[count] = new_phone_number;

    cout<< "please enter your name: ";
    string new_name;
    getline (cin, new_name);
    name[count] = new_name;

    count++;
}

int main()
{
    string a;
    cin>> a;
    if(a == 1){
        insert_data();
    }

}
Blaze
  • 16,736
  • 2
  • 25
  • 44
John
  • 3
  • 5
  • 2
    Unrelated, `if(a == 1)` - that isn't valid C++ code. – WhozCraig Oct 26 '18 at 08:05
  • 1
    That won't compile, and it should misbehave even without the conditional, because of [this problem](https://stackoverflow.com/questions/21567291/why-does-stdgetline-skip-input-after-a-formatted-extraction) – molbdnilo Oct 26 '18 at 08:13

2 Answers2

3

" please enter phone number: please enter your name: in the same line" but I need like the first "please enter your phone number: 4545 in the next line please enter your name: dddf

What you need to use is std::endl. It stands for "end the line and flush the stream" and will insert a new line in your output. Change this:

cout<< "please enter your name: ";

To this:

cout << endl << "please enter your name: ";

To insert a new line before that line, resulting in this output:

please enter your phone number: 4545
please enter your name: dddf

Also, you should probably change this:

if(a == 1){
    insert_data();
}

To just that:

insert_data();

I'm amazed that the if(a == 1) even works, looking at the documentation it's probably casting the 1 to a const char* for string comparison. Either way it's nonsense and probably doesn't do what you intended.

Blaze
  • 16,736
  • 2
  • 25
  • 44
  • unfortunately `std::endl` does not really stand for "end the line" but for "end the line and flush the stream". "end the line" is `'\n'` – 463035818_is_not_an_ai Oct 26 '18 at 08:36
  • Thanks for the correction, I added it to the answer. – Blaze Oct 26 '18 at 08:37
  • the problem is if I will put if statement then it is not posible to give the input in from the console for the "please enter phone number: "; And I need if statement – John Oct 26 '18 at 22:33
0

The problem was that in one side I used getline in another cin

John
  • 3
  • 5