我想从文件中一起读取像“Penelope Pasaft”这样的名称并将其保存到变量“person”。我明白我必须使用get line(文件,人)。但是我有一个问题,因为我还想在之前阅读其他变量。 想象一下.txt就像:
1
546343864246
Penelope Pasaft
所以这是代码:
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
答案 0 :(得分:1)
问题是你的输入文件中有空行。
如果您仅使用cin >>
,它将正常工作,因为>>
运算符会跳过空白字符(但会停留在空白字符处,如您所说:不能全部使用)
另一方面,getline
将读取该行,即使它是空白的。
我建议从您的稍微修改以下独立代码:注意循环直到文件结尾或非空白行。 (注意:只有行中有空格,才会失败)
我还用矢量替换了数组,动态调整大小(更多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