我正在使用 C++ 编写程序,我需要从文件中读取整个文本字符串。该文件在其中一行中包含一个地址,例如“123 Easy Ave”,必须将其拉入一个字符串或字符中。这是我的代码:
数据文件:
Matt Harrold
307C Meshel Hall
1000 .01 4
数据由成为 CustomerName 的名字和姓氏组成,下一行是要填充 Address 的地址,然后是三个数字:principal、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”并停在空格处...非常感谢您的帮助!
最佳答案
编辑:为了回应对我的问题的反馈,我对其进行了编辑以使用更合适的 std::getline
。而不是 std::istream::getline
.这两个就足够了,但是std::getline
更适合 std::string
s,您不必担心指定字符串大小。
使用 std::getline()
来自 <string>
.
这里有一个很好的引用和示例:http://www.cplusplus.com/reference/string/getline/ .
您还需要小心组合提取 ( >>
) 运算符和 getline
.这个问题的最佳答案 ( cin>> not work with getline() ) 简要解释了为什么它们不应该一起使用。简而言之,调用 cin >>
(或您正在使用的任何输入流)在流中留下一个换行符,然后由 getline
拾取,给你一个空字符串。如果你真的想一起使用它们,你必须调用std::istream::ignore
在两次调用之间。
关于c++ - 从 C++ 文件中读取整行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8351834/