中的文件读取整行

中的文件读取整行

本文介绍了从c ++中的文件读取整行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用c ++中的程序,我需要从文件中读取整个文本字符串。该文件包含一行上的地址,像这样123 Easy Ave,这必须拉入一个字符串或字符。这是我的代码:

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:

数据文件:

Matt Harrold
307C Meshel Hall
1000 .01 4

最后一行是要填充地址的地址,然后是三个数字:principle,InterestRate,Years。

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.

代码:

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;

现在它只会拉入103C并停在空间...帮助非常感谢!

Right now it only pulls in "103C" and stops at the space... Help is greatly appreciated!

推荐答案

编辑:为了回应对我问题的反馈,我编辑它使用更合适的 std :: getline 而不是 std :: istream :: getline 。这两个都足够了,但 std :: getline 更适合 std :: string

In response to feedback on my question, I have edited it to use the more appropriate std::getline instead of std::istream::getline. Both of these would suffice, but std::getline is better suited for std::strings and you don't have to worry about specifying the string size.

使用 std :: getline()< string>

这里有一个很好的参考和例子:。

There is a good reference and example here: http://www.cplusplus.com/reference/string/getline/.

您还需要小心地组合提取(>> )运算符和 getline 。此问题的最高答案()简要解释为什么它们不应该一起使用。简而言之,调用 cin>> (或您使用的任何输入流)在流中留下换行符,然后由 getline ,给你一个空字符串。如果你真的想一起使用它们,你必须在两个调用之间调用 std :: istream :: ignore

You'll also need to be careful combining the extraction (>>) operator and getline. The top answer to this question (cin>> not work with getline()) explains briefly why they shouldn't be used together. In short, a call to cin >> (or whatever input stream you are using) leaves a newline in the stream, which is then picked up by getline, giving you an empty string. If you really want to use them together, you have to call std::istream::ignore in between the two calls.

这篇关于从c ++中的文件读取整行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 17:31