C++中文本的读入
读入文本文件
标准库包含逐行读取文本文件的功能。然后,你可以一次一行地解析文本文件的每一行。
比如说,你有文件,其中使用数字和逗号表示一个 3x4 的矩阵:
, , , 10.5
, 15.2, ,
, , , 7.5
你想读入这个文件,并创建一个二维矢量来表示矩阵。下面是参考代码。你可以在下面运行代码,看看它是否可以运行。
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector> using namespace std; int main() { // initialize string variables for reading in text file lines
string line;
stringstream ss; // initialize variables to hold the matrix
vector < vector <float> > matrix;
vector<float> row; // counter for characters in a text file line
float i; // read in the file
ifstream matrixfile ("matrix.txt"); // read in the matrix file line by line
// parse the file if (matrixfile.is_open()) {
while (getline (matrixfile, line)) { // parse the text line with a stringstream
// clear the string stream to hold the next line
ss.clear();
ss.str("");
ss.str(line);
row.clear(); // parse each line and push to the end of the row vector
// the ss variable holds a line of text
// ss >> i puts the next character into the i variable.
// the >> syntax is like cin >> some_value or cout << some_value
// ss >> i is false when the end of the line is reached while(ss >> i) {
row.push_back(i); if (ss.peek() == ',' || ss.peek() == ' ') {
ss.ignore();
}
} // push the row to the end of the matrix
matrix.push_back(row);
} matrixfile.close(); // print out the matrix
for (int row = ; row < matrix.size(); row++) {
for (int column = ; column < matrix[row].size(); column++) {
cout << matrix[row][column] << " " ;
}
cout << endl;
}
} else cout << "Unable to open file"; return ;
}
下面是从文本文件读取数据的示范。代码读取包含矩阵数据的一个图块文件。然后代码将矩阵输出到终端显示器。通读代码,想想它的功能是什么。然后按“测试运行”按钮运行代码。
main.cpp
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector> using namespace std; int main() { // initialize string variables for reading in text file lines
string line;
stringstream ss; // initialize variables to hold the matrix
vector < vector <float> > matrix;
vector<float> row; // counter for characters in a text file line
float i; // read in the file
ifstream matrixfile ("matrix.txt"); // read in the matrix file line by line
// parse the file if (matrixfile.is_open()) {
while (getline (matrixfile, line)) { // parse the text line with a stringstream
// clear the string stream to hold the next line
ss.clear();
ss.str("");
ss.str(line);
row.clear(); // parse each line and push to the end of the row vector
while(ss >> i) {
row.push_back(i); if (ss.peek() == ',' || ss.peek() == ' ') {
ss.ignore();
}
} // push the row to the end of the matrix
matrix.push_back(row);
} matrixfile.close(); // print out the matrix
for (int row = ; row < matrix.size(); row++) {
for (int column = ; column < matrix[row].size(); column++) {
cout << matrix[row][column] << " " ;
}
cout << endl;
}
} else cout << "Unable to open file"; return ;
}
matrix.txt
, , , 10.5
, 15.2, ,
, , , 7.5
fstream 提供读入和输出文件的函数和类。
这行代码读取文件 “matrix.txt”,然后创建一个名为 “matrixfile” 的对象,你可以使用该对象读入文本文件:
ifstream matrixfile ("matrix.txt");
下面的 if 语句检查文件是否正确打开:
if (matrixfile.is_open()) {
然后 while 循环一次读取一行文件。每行都放在一个名为 “line” 的变量里:
if (matrixfile.is_open()) {
while (getline (matrixfile, line)) {
如果你查看文本文件,可以看到本例中每一行都是由浮点数、逗号和空格组成的字符串。例如,"1, 6, 2, 10.5"。
标准库中的 sstream 文件提供了操作和解析字符串的功能。在代码中你会看到,首先声明了一个 sstream 对象,然后使用 ss 对象遍历并解析文本文件的每一行:
stringstream ss; .... ss.clear();
ss.str("");
ss.str(line); while(ss >> i) {
row.push_back(i); if (ss.peek() == ',' || ss.peek() == ' ') {
ss.ignore();
}
}
换句话说,代码找到了一个浮点数,并将该数添加到名为 rows 的向量中。ss.peek()这一行查看下一个字符,检查它是逗号还是空格,并忽略逗号或空格。
同样需要注意的是,当你完成读入文件时,一定要保持关闭文件的好习惯。
matrixfile.close();
如果你编写的程序可以同时打开许多文件,并且永远不会关闭文件,那么程序可能会崩溃。
C++中文本的读入的更多相关文章
- DOM中文本节点索引方法
问题 对于 jquery 接口text()只能取到有标签的 dom对象中 文本内容. 如果索引对象本身就是文本节点,则不好索引到, 没有相关的索引选择器. 例如: 对于<input>aaa ...
- Asp.Net中文本换行
Asp.Net中文本换行 VB.NET Function HtmlCode(ByVal fString) If fString <> "" Then ...
- css中文本框与按钮对不齐解决方案
我们先对对input标记设定样式,代码如下: html 代码 <form> <input type=”text” name=”text1” id=”text1” /> < ...
- C#中文本模板(.tt)
关于C#中文本模板(.tt)的简单应用 这两天做项目突遇 .tt文件,之前没有接触过,so查询学习做笔记,帮助记忆和后来者. 在项目添加中点击选择文本模板 下面贴出代码,做了简单的注释 1 2 3 4 ...
- T4((Text Template Transformation Toolkit))模版引擎之基础入门 C#中文本模板(.tt)的应用
1 关于C#中文本模板(.tt)的简单应用https://blog.csdn.net/zunguitiancheng/article/details/78011145 任何一个傻瓜都能写出计算机能理解 ...
- 从NLP任务中文本向量的降维问题,引出LSH(Locality Sensitive Hash 局部敏感哈希)算法及其思想的讨论
1. 引言 - 近似近邻搜索被提出所在的时代背景和挑战 0x1:从NN(Neighbor Search)说起 ANN的前身技术是NN(Neighbor Search),简单地说,最近邻检索就是根据数据 ...
- 【msdn wpf forum翻译】TextBox中文本 中对齐 的方法
原文:[msdn wpf forum翻译]TextBox中文本 中对齐 的方法 原文链接:http://social.msdn.microsoft.com/Forums/en-US/wpf/threa ...
- 如何设置HTML页面中文本的字体
字体属性介绍 CSS中的字体属性是干什么的呢?字体字体肯定和字体有关咯,就是设置HTML页面中文本的字体, CSS中常用的字体属性有几种呢,笔者给大家梳理了下,比较常用的一共有5种,今天我们就看看这5 ...
- CSS中文本继承情况
无继承性的属性 http://www.cnblogs.com/thislbq/p/5882105.html vertical-align: 垂直文本对齐 CSS中文本可以继承父级样式 体 ...
随机推荐
- python模拟浏览器文件上传,csrf放行
服务器端视图函数 from django.shortcuts import render,HttpResponse from django.views.decorators.csrf import c ...
- 学习Boost/Asio
编译boost 在Mac下使用brew编译boost,为了使用C++11,需要加入参数–c++11 $ brew install boost --c++11 在我的Mac虚拟机里面用了20分钟左右编译 ...
- 洛谷P1003 [NOIP2011提高组Day1T1]铺地毯
P1003 铺地毯 题目描述 为了准备一个独特的颁奖典礼,组织者在会场的一片矩形区域(可看做是平面直角坐标系的第一象限)铺上一些矩形地毯.一共有 n 张地毯,编号从 1 到n .现在将这些地毯按照编号 ...
- 洛谷P1077 [NOIP2012普及组]摆花 [2017年四月计划 动态规划14]
P1077 摆花 题目描述 小明的花店新开张,为了吸引顾客,他想在花店的门口摆上一排花,共m盆.通过调查顾客的喜好,小明列出了顾客最喜欢的n种花,从1到n标号.为了在门口展出更多种花,规定第i种花不能 ...
- Mysql 5.7.17安装后登录mysql的教程方法
在运行 ./bin/mysqld Cinitialize 初始化数据库时,会生成随机密码,示例: [Note] A temporary password is generated for root@l ...
- Django项目:CRM(客户关系管理系统)--14--06PerfectCRM实现King_admin注册功能获取内存优化处理
<th >{% get_app_name admin_class.model %}{{ admin_class }} </th> #kingadmin_tags.py # —— ...
- 【linux配置】Linux系统下安装rz/sz命令以及使用说明
Linux系统下安装rz/sz命令以及使用说明 对于经常使用Linux系统的人员来说,少不了将本地的文件上传到服务器或者从服务器上下载文件到本地,rz / sz命令很方便的帮我们实现了这个功能,但是很 ...
- Ubuntu卸载通过apt-get命令安装的软件
卸载一个已安装的软件包(删除配置文件): apt-get --purge remove packagename
- 麻烦把JS的事件环给我安排一下
上次大家跟我吃饱喝足又撸了一遍PromiseA+,想必大家肯定满脑子想的都是西瓜可乐...... 什么西瓜可乐!明明是Promise! 呃,清醒一下,今天大家搬个小板凳,听我说说JS中比较有意思的事件 ...
- git命令入门
http://www.cocoachina.com/ios/20160629/16855.html 译者序:这是一篇给像我这样的新手或者是熟悉图形工具的老鸟看的.仅作为快速入门的教程. git 现在的 ...