逐行读取C 的文件
Reading a file line by line in c++
我正在尝试在大学中为我的C 类做这个项目,并且我在逐行阅读文本文件,然后将文本从文件输出到控制台。这是我拥有的代码:
void readFile()
{
cout << "Reading Text File" << endl << endl;
int huge, large, medium, small, remainder;
string line0, line1, line2, line3, line4, line5, line6, numberOrdered;
ifstream fin;
fin.open("DoflingyOrder.txt");
while(getline(fin,numberOrdered))
{
getline(fin, line1);
cout << "Name: " << line1 << endl;
getline(fin, line2);
cout << "Street Address: " << line2 << endl;
getline(fin, line3);
cout << "City, State and Zip Code: " << line3 << endl;
getline(fin, numberOrdered);
cout << "Number of Doflingies Ordered: " << numberOrdered << endl << endl;
}
它忽略了文本文件中的名称,这意味着它是一条线路。有什么建议么?如果有人需要,我可以将文本文件和.cpp文件上传到Dropbox。
这是文本文件的示例:
莱斯利·诺(Leslie Knope) 普利茅斯街1456号 Pawnee,47408 356
Ann Perkins 217 Lowell Drive Pawnee,47408 9
汤姆·哈德福德 689 Lil Sebastian Avenue Pawnee,47408 1100
" Leslie Knope"之前没有空间。
您最终发布的输入...
Leslie Knope 1456 Plymouth Street Pawnee,47408 356
Ann Perkins 217 Lowell Drive Pawnee,47408 9
汤姆·哈德福德689 Lil Sebastian Avenue Pawnee,47408 1100
...揭示您的所有getline
s都是错误的,因为它们一次读取了整个行(默认情况下)。
实际上,这是一个相当困难/痛苦的问题。数据,一个完美的解决方案非常困难,因为某些地址可能是说很难与人名称的一部分区分开的建筑物名称,而多词的城镇名称与早期地址详细信息的末尾很难区分。一种合理的教育解决方案可能是:
#define EXPECT(X)
do {
if (!(X)) throw std::runtime_error("EXPECT(" #X ")");
} while (false)
std::string first, last;
std::string street, town_state_postcode;
int num;
std::string word;
while (fin >> first)
{
EXPECT(fin >> last);
while (fin >> word)
{
if (word[word.size() - 1] != ',')
if (street.empty())
street = word;
else
street += ' ' + word;
else // trailing comma indicates town
{
town_state_postcode = word; // town
EXPECT(fin >> word); // state
town_state_postcode += ' ';
town_state_postcode += word;
EXPECT(fin >> word);
town_state_postcode += ' ';
town_state_postcode += word;
EXPECT(fin >> numberOrdered);
// SUCCESS use the data here
// ...
}
}
}
上面的代码使这些简单的假设:
名称由名字和姓氏组成
城镇名称是一个单词,带有尾巴逗号
,对于使用现实世界数据的更加精确的解决方案,您需要创建例如可能终止"街道"的单词地址的一部分,例如"驱动器"大街"大街"等等。如果您可以获取创建的文本文件以将某些分离器注入结构的数据(甚至切换到XML之类的东西)。
string line;
for(int i=0;;i++)
{
if(!getline(fin,line))break;
if(i%4==0)cout<<"Name: "<<line<<endl;
else if(i%4==1)cout<<"Street Address: " << line<< endl;
else if(i%4==2)cout<<"City, State and Zip Code: " << line << endl;
else cout << "Number of Doflingies Ordered: " << line << endl << endl;
}
我建议使用!跳过名称列。
- 正在将csv文件读取为双精度矢量
- 将从格式化文本文件读取的文本数据存储到链表
- C++ 读取文件读取文件不正确
- 使用对象文件读取三角形数据网格
- 如何减慢从 BVH 文件读取的 opengl 动画?
- 从文件读取,并写入函数C++中的数组
- 从对象C++中的文件读取内容时出现分段错误
- 从文件读取并通过矢量输出到控制台
- 尝试将字符串从文件读取到无符号字符向量中
- 如何将文本文件读取到二维数组中并以 c++ 打印
- 简化文件读取的函数
- 如何将逗号分隔的文件读取为 2D int 数组?
- 在 c++ 中将数据从文件读取到队列中
- 'std::wstring_convert'尽可能多地转换(从 UTF8 文件读取块)
- C++,从文件读取到结构,然后读取到向量(结构被推入向量太多次,而不仅仅是一次)
- 文件读取C++包括空格键
- 从文件读取时未将值推回矢量
- 从文件 C++ 读取时的无限循环
- 从同一文件读取和写入?
- 从.txt文件读取到C++中的双精度向量