【发布时间】:2021-02-03 23:36:54
【问题描述】:
我正在尝试读取一个包含多行的文件,其中每一行都有一个单词,然后是一个空格,后跟该单词的简短描述。
文本文件示例:
你好 一种问候 时钟 告诉我们时间的设备 .末尾的句号 (.) 表示没有更多行可读取。
我尝试了一种在getline() 函数中使用分隔符的方法,但只成功读取了文件的一行。我想将第一个单词(在第一个空格之前)存储在一个变量中,比如word,并将描述(在第一个空格之后的单词,直到遇到换行符)存储在另一个变量中,比如desc。
我的方法:
#include <iostream>
#include <fstream>
#include <string.h>
using namespace std;
int main()
{
string filename = "text.txt" ;
ifstream file (filename);
if (!file)
{
cout<<"could not find/open file "<<filename<<"\n";
return 0;
}
string word;
string desc;
string line;
while(file){
getline(file,line,' ');
word = line;
break;
}
while(file){
getline(file,line,'\n');
desc = line;
break;
}
file.close();
cout<<word<<": ";
cout<<desc<<"\n";
return 0;
}
上述代码的输出为:
hello: A type of greeting
我尝试在上面编写的循环中添加另一个父循环while,条件为file.eof(),但随后程序永远不会进入两个子循环。
【问题讨论】:
-
@buildsucceeded 否,因为仅在 读取不成功后才设置 eof。但是在 Frexpe:您是否尝试过使用 Google 或本网站的搜索功能?这个问题被问过很多次了,网上有很多例子
-
改用
while(getline(file,line,'\n')) { desc = line;}。 -
阅读好的 C++ programming book 并查看 this C++ reference,也许还有 C++11 标准 n3337。从现有的 C++ 开源项目(例如 GCC 或 RefPerSys 或 fish...)中获取灵感。阅读他们的文档后使用GCC 和GDB
标签: c++ file multiline getline