Hi all, I'm doing a question for my assignment on functions. The question wants me to create two functions to input and display data entered by the user but i'm new to strings and i cannot seem to get my program to work correctly, i am also not sure how i would use the information gained by the inputData function that im using to display the information later. Any help would be great.
Heres my code:
#include <iostream>
#include <string>
using namespace std;
string inputData(string name,string addr1,string addr2,string postalCode)
{
cout << "Please enter your name:" << endl;
cin >>name;
cout << "Please enter your postal address1:" << endl;
cin >>addr1;
cout << "Please enter your postal address2:" << endl;
cin >>addr2;
cout << "Please enter your postalCode:" << endl;
cin >>postalCode;
You should use the getline function to get a string of input instead of cin, that way if some puts in their full name you get the whole thing. Cin only grabs input until it finds a space, then discards the space from the input stream. Getline grabs input until it finds a newline character, then discards the newline character form the stream.
You can use getline like this:
1 2
getline(cin, name); //gets line from cin input stream, puts into name string
//getline also works for other types of input streams.
If your running this on console you can include <cstdlib.h> and call the system function to pause the console, assuming your on windows:
1 2 3 4 5
#include <cstdlib.h>
system("pause");
//put this after you get your data, so that you can read it without
//console closing.
display data function needs to take the strings as inputs instead of declaring them inside it, like this:
Thanks for the reply, ive changed my code around a bit after what you said i should do, the program runs until i enter anything for the postalCode variable and then the program stops working and windows shuts it down. Do you have any idea why this would be happening?
string inputData(string name,string addr1,string addr2,string postalCode)
{
cout << "Please enter your name:" << endl;
getline(cin,name);
cout << "Please enter your postal address1:" << endl;
getline(cin,addr1);
cout << "Please enter your postal address2:" << endl;
getline(cin,addr2);
cout << "Please enter your postalCode:" << endl;
getline(cin,postalCode);
}
Ah I see whats wrong, you need to take the string in by reference so the functions can modify them directly. Whats happening is the inputData function is copying them into its scope, instead of modifying the external strings.
If you change your functions to these it will work: