我想从一个文件中读取一个像“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/