c++ - 如何使用 get line() 从文件中读取间隔字符串?

标签 c++

我想从一个文件中读取一个像“Penelope Pasaft”这样的名字,并将它保存到一个变量“person”中。我明白我必须使用 get 行(文件,人)。但是我这样做有问题,因为我之前还想阅读其他变量。 想象一个像这样的 .txt:


1

+546343864246

佩内洛普·帕萨夫特


代码如下:

typedef struct {

    string number; //I use string because it is an alphanumeric cellphone number 
    string person;
    int identifier;
} cellphone;

ifstream entry;

entry.open(fileName.c_str());

cellphone c[10];

int j=0;

    if(entry)
    {
        cout << "The file has been successfully opened\n\n";
        while(!entry.eof())
        {
            entry >> c[j].identifier >> c[j].number;
            getline(entry,c[j].person);

            cout << "Start: " << c[j].identifier << "\nNumber: " <<
                c[j].number << "\nPerson: " << c[j].person << endl << endl;
            j++;
        }
    }

我遇到的问题是它似乎没有打印或保存任何数据到变量 c[j].person

最佳答案

问题是您的输入文件中有空行。

如果您仅使用 cin >>,它会正常工作,因为 >>> 运算符会跳过空白字符(但会停在空白字符处,如您所述:can't拥有一切)

另一方面,getline 将读取该行,即使它是空白的。

我建议对以下独立代码稍作修改:注意循环直到文件末尾或非空行。 (注意:如果行中只有空格,会失败)

我还用 vector 替换了数组,动态调整了大小(更多 C++-ish)

#include<iostream>
#include<fstream>
#include<string>
#include<vector>
using namespace std;

typedef struct {

    string number; //I use string because it is an alphanumeric cellphone number 
    string person;
    int identifier;
} cellphone;


int main()
{

ifstream entry;
string fileName = "file.txt";
entry.open(fileName.c_str());

vector<cellphone> c;

cellphone current;

int j=0;

    if(entry)
    {
        cout << "The file has been successfully opened\n\n";
        while(!entry.eof())
        {
            entry >> current.identifier >> current.number;
            while(!entry.eof())
            {
            getline(entry,current.person);
            if (current.person!="") break;  // stops if non-blank line
            }
            c.push_back(current);

            cout << "Start: " << c[j].identifier << "\nNumber: " << c[j].number << "\nPerson: " << c[j].person <<endl<<endl;
            j++;
        }
    }
    return 0;
}  

输出:

The file has been successfully opened

Start: 1
Number: +546343864246
Person: Penelope Pasaft

关于c++ - 如何使用 get line() 从文件中读取间隔字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39376190/

相关文章:

c++ - C++、Python 3.7.4、SWIG 4.0.0 和 Windows 10 的问题 - ModuleNotFoundError

c++ - 关于Visual C++中预编译头文件的问题

c++ - char temp[3] =""; 是什么意思?

c++ - 我如何在初始化列表中的构造函数之后初始化变量/对象?

c++ - ESRI map 对象 - 是否可以禁用 MouseWheel 事件处理程序?

C++ 在结构中存储函数和运算符

c++ - std::find 和 boost::make_indirect_iterator - 编译错误

C++ Direct 2D 如何调整 ID2D1Bitmap 的大小

c++ - 使用一个 Makefile 构建多个共享库

c++ - 最后一行被打印两次(C++)