C++ C++;ifstream的getline函数帮助

C++ C++;ifstream的getline函数帮助,c++,ifstream,getline,C++,Ifstream,Getline,因此,我正在编写一个程序,处理文件的读写。我使用getline()函数是因为文本文件中的某些行可能包含多个元素。到现在为止,我在getline上从未遇到过问题。这是我得到的 文本文件如下所示: John Smith // Client name 1234 Hollow Lane, Chicago, IL // Address 123-45-6789 // SSN Walmart

因此,我正在编写一个程序,处理文件的读写。我使用getline()函数是因为文本文件中的某些行可能包含多个元素。到现在为止,我在getline上从未遇到过问题。这是我得到的

文本文件如下所示:

  John Smith                       // Client name
  1234 Hollow Lane, Chicago, IL    // Address
  123-45-6789                      // SSN
  Walmart                          // Employer
  58000                            // Income
  2                                // Number of accounts the client has
  1111                             // Account Number
  2222                             // Account Number
ifstream inFile("ClientInfo.txt");
if(inFile.fail())
{
    cout << "Problem opening file.";
}
else
{
    string name, address, ssn, employer;
    double income;
    int numOfAccount;

    getline(inFile, name);
    getline(inFile, address);
    // I'll stop here because I know this is where it fails.
代码如下:

  John Smith                       // Client name
  1234 Hollow Lane, Chicago, IL    // Address
  123-45-6789                      // SSN
  Walmart                          // Employer
  58000                            // Income
  2                                // Number of accounts the client has
  1111                             // Account Number
  2222                             // Account Number
ifstream inFile("ClientInfo.txt");
if(inFile.fail())
{
    cout << "Problem opening file.";
}
else
{
    string name, address, ssn, employer;
    double income;
    int numOfAccount;

    getline(inFile, name);
    getline(inFile, address);
    // I'll stop here because I know this is where it fails.
ifstream-infle(“ClientInfo.txt”);
if(infle.fail())
{

cout您显示的代码应该适用于该文件。因此,某些内容一定与您认为的不同。最可能的原因是:

  • 该文件实际上有一个换行符,您认为它只有一个空格
  • 代码使用
    infle>>name
    您认为它使用
    getline(infle,name)
  • 可能您更改了某些内容,忘记保存或重新编译,或者您正在读取的文件与您想象的不同


    顺便说一句,从变量声明来看,您可能计划将
    getline()
    调用与提取运算符调用(如
    infle>>income
    )混合在一起。混合这些调用需要小心,因为提取运算符会留下后面的空格
    getline()
    可能会阅读。在底部附近有更多信息。

    此程序按照我的预期编译和工作。您确定以前没有类似于
    cin>>name;cin>>address;
    的内容被替换为
    getline
    ,只是在测试之前忘记保存源文件和/或重新编译程序再次ng?WFM(适用于我)。我将您的代码粘贴到源文件中,添加了各种include和
    std::
    前缀,将文本粘贴到
    ClientInfo.txt
    文件中(删除//注释),在
    std::cout
    中添加了一行打印
    name
    ,编译并运行。
    name
    对我来说是
    John Smith
    。你为什么要使用c-style
    getline
    而不是
    istream::getline
    ?@dmckee他正在使用
    std::getline
    。他显然有一个
    使用名称空间std;
    作为ev通过使用原始
    ifstream
    string
    而不使用名称空间限定符,这是正确的。顺便说一句,请注意
    std::getline
    可以支持读取
    std::string
    ,但是
    istream::getline
    只会读取
    char*
    。好的,我已经开始工作了,但我遇到了另一个问题,假设我在文件中有两个客户端,它可以读取第一个客户端,但在获取第二个客户端的名称之前,getline会读入一个“。为什么这样做。如果不清楚,请告诉我。