c++ - 从 C++ 文件中读取整行

标签 c++ string file

我正在使用 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/

相关文章:

c++ - 返回序列 CORBA C++ 服务器 Java 客户端时出现段错误

c++ - 分配器 : how are the standard containers expected to work internally?

c++ - for 语句中的 constexpr

正则表达式捕获两个数字之间的第一个字符串

java - 如何读取以逗号分隔的文件

loops - 使用 goroutine 无限期地迭代文件

c++ - 索引超出 vector 类范围时没有编译错误或运行时错误?

JavaScript 如何将字符串转换为函数

c++ - 关于c++中的 'compare'函数

android - 如何在 Android 中选择一个文件并计算其哈希值 (SHA-256)