I am working on a program in c++ and I need to read an entire string of text from a file. The file contains an address on one of the lines like this “123 Easy Ave” this has to be pulled into one string or char. Here is the code I have:
The data file:
Matt Harrold
307C Meshel Hall
1000 .01 4
The data is made up of a first and last name which become CustomerName, the next line is the address which is to populate Address, Then three numbers: principle, InterestRate, Years.
The code:
float InterestRate = 0;
int Years = 0;
char Junk [20];
int FutureValue;
float OnePlusInterestRate;
int YearNumber;
int count = 0;
char CustomerName;
string Address;
int * YearsPointer;
CustomerFile >> CustomerName
>> Address
>> Principle
>> InterestRate
>> Years;
Right now it only pulls in “103C” and stops at the space… Help is greatly appreciated!
Edit: In response to feedback on my question, I have edited it to use the more appropriate
std::getlineinstead ofstd::istream::getline. Both of these would suffice, butstd::getlineis better suited forstd::strings and you don’t have to worry about specifying the string size.Use
std::getline()from<string>.There is a good reference and example here: http://www.cplusplus.com/reference/string/getline/.
You’ll also need to be careful combining the extraction (
>>) operator andgetline. The top answer to this question (cin>> not work with getline()) explains briefly why they shouldn’t be used together. In short, a call tocin >>(or whatever input stream you are using) leaves a newline in the stream, which is then picked up bygetline, giving you an empty string. If you really want to use them together, you have to callstd::istream::ignorein between the two calls.