C++文件读(逐行读、逐单词读)

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

int main()
{
vector text;//创建vector对象
ifstream ifile;//创建输入文件流对象
ifile.open("Test.txt",ifstream::in);//打开文件
if(!ifile)//判断是否打开成功
cerr<<"open failed"<<endl;
//初始化vector对象
string line,word;
while(getline(ifile,line))//逐行读
{
istringstream istrm(line);//创建字符串流
while(istrm>>word)//逐单词读
text.push_back(word);
}
ifile.clear();
ifile.seekg(0);//文件重定位
while(ifile>>word) cout<<word<<endl;//逐单词读
ifile.close();//关闭文件
vector::iterator it=text.begin();
while(it!=text.end())//遍历vector容器
{
cout<<*it++<<ends;
}
return 1;
}

注:
1.ifstream的对象可直接用于文件的逐单词读(ifstream的头文件为fstream)
2.getline函数可直接获取某一行
3.istringstream的对象可用于文本的逐单词读(istringstream的头文件为sstream)
  • 1
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个可以打开文件取英语单词并建立词典的 C++ 代码示例: ```c++ #include <iostream> #include <fstream> #include <sstream> #include <map> #include <string> using namespace std; int main() { // 定义一个 map 对象,用于存储单词和定义 map<string, string> dictionary; // 打开文件单词和定义 ifstream file("dictionary.txt"); string line; while (getline(file, line)) { stringstream ss(line); string word, definition; ss >> word >> definition; dictionary[word] = definition; } file.close(); // 从字典中查找单词 string word; cout << "Enter a word to look up: "; cin >> word; if (dictionary.find(word) != dictionary.end()) { // 如果单词存在,输出其定义 cout << dictionary[word] << endl; } else { // 如果单词不存在,输出错误信息 cout << "Sorry, the word \"" << word << "\" is not in the dictionary." << endl; } return 0; } ``` 这个程序首先打开名为 `dictionary.txt` 的文件,并逐行单词和定义。每行的第一个单词被当作键,第二个单词被当作值,存储到 `map` 对象中。然后程序询问用户输入一个要查找的单词,并在字典中查找该单词。如果单词存在,输出其定义;否则输出错误信息。 注意,这里的 `dictionary.txt` 文件应该按照单词和定义的格式进行编写,每行一个单词和其对应的定义,中间用空格隔开。例如: ``` apple a round fruit with red or green skin and a white inside banana a long curved fruit with a yellow skin chocolate a sweet brown food that is made from cocoa beans ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值