1

Hi guys please check this code. I want to create a program in which I will be prompted to enter first name and last name then output it in chronological order without having to create variable for each first name and last name.

#include<iostream>
using namespace std;
int main(){

int fname[9];
int lname[9];
int x;

while (x < 10){
    cout<<"Enter first name: ";
    cin>>fname[0];
    cout<<"Enter last name: ";
    cin>>lname[0];
    x = x + 10;
}

x = 0;

while (x < 10){
    cout<<fname[0]<<" "<<lname[0]<<"\n";
    x = x + 1;
}

return 0;
}
4
  • 1
    Why are you using int arrays for text input? Commented Nov 4, 2015 at 15:24
  • 1
    while (x<10){ /*...*/ x = x+10;} will execute exactly once. Also the second while loop is broken: You write the same stuff 10 times. Commented Nov 4, 2015 at 15:30
  • so string fname[0] = ""; then how about for the loop? I need to store data sequentially and then print it after. Commented Nov 4, 2015 at 15:31
  • @nyelnyelnyel Just start with a std::vector<std::string>> and please dont abuse while loops when a simple for loop would be much clearer Commented Nov 4, 2015 at 15:32

1 Answer 1

1

Your arrays should be type strings, rest of the code should look like this:

for(int x=0;x<10;x++) {
    cout<<"Enter first name: ";
    cin>>fname[x];
    count<<"Enter last name: ";
    cin>>lname[x];
}
for(x=0;x<10;x++){
    cout<<fname[x]<<" "<<lname[x]<<"\n";
}

return 0;
}

In your own snippet you're printing the first element of your arrays 10 times, this will print the x-th element while x goes from 0 to 9.

Sign up to request clarification or add additional context in comments.

2 Comments

I can't print the names. The program lags after I input the names. "Untitled1.exe has stopped working"
Can you post the code you're using as this is only a snippet that I posted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.