读入文本文件

标准库包含逐行读取文本文件的功能。然后,你可以一次一行地解析文本文件的每一行。

比如说,你有文件,其中使用数字和逗号表示一个 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++中文本的读入的更多相关文章

  1. DOM中文本节点索引方法

    问题 对于 jquery 接口text()只能取到有标签的 dom对象中 文本内容. 如果索引对象本身就是文本节点,则不好索引到, 没有相关的索引选择器. 例如: 对于<input>aaa ...

  2. Asp.Net中文本换行

    Asp.Net中文本换行 VB.NET Function HtmlCode(ByVal fString)        If fString <> "" Then    ...

  3. css中文本框与按钮对不齐解决方案

    我们先对对input标记设定样式,代码如下: html 代码 <form> <input type=”text” name=”text1” id=”text1” /> < ...

  4. C#中文本模板(.tt)

    关于C#中文本模板(.tt)的简单应用 这两天做项目突遇 .tt文件,之前没有接触过,so查询学习做笔记,帮助记忆和后来者. 在项目添加中点击选择文本模板 下面贴出代码,做了简单的注释 1 2 3 4 ...

  5. T4((Text Template Transformation Toolkit))模版引擎之基础入门 C#中文本模板(.tt)的应用

    1 关于C#中文本模板(.tt)的简单应用https://blog.csdn.net/zunguitiancheng/article/details/78011145 任何一个傻瓜都能写出计算机能理解 ...

  6. 从NLP任务中文本向量的降维问题,引出LSH(Locality Sensitive Hash 局部敏感哈希)算法及其思想的讨论

    1. 引言 - 近似近邻搜索被提出所在的时代背景和挑战 0x1:从NN(Neighbor Search)说起 ANN的前身技术是NN(Neighbor Search),简单地说,最近邻检索就是根据数据 ...

  7. 【msdn wpf forum翻译】TextBox中文本 中对齐 的方法

    原文:[msdn wpf forum翻译]TextBox中文本 中对齐 的方法 原文链接:http://social.msdn.microsoft.com/Forums/en-US/wpf/threa ...

  8. 如何设置HTML页面中文本的字体

    字体属性介绍 CSS中的字体属性是干什么的呢?字体字体肯定和字体有关咯,就是设置HTML页面中文本的字体, CSS中常用的字体属性有几种呢,笔者给大家梳理了下,比较常用的一共有5种,今天我们就看看这5 ...

  9. CSS中文本继承情况

    无继承性的属性 http://www.cnblogs.com/thislbq/p/5882105.html   vertical-align:  垂直文本对齐   CSS中文本可以继承父级样式   体 ...

随机推荐

  1. JavaScript类型转换规则

    注:JavaScript相对于其他强类型(如c,c++,java,定义变量的同时申明变量类型)语言来说,是弱类型和松散型(在定义的时候不需要申明变量类型,在使用的时候才赋值给她什么类型就是什么类型.所 ...

  2. python基础--反射、元类、单例设计模式

    反射:reflect,反射指的是一个对象应该具备可以检测.修改.增加自身属性的能力,反射就是通过字符串操作属性 hasattr(对象,带查询的属性名称) 判断某个对象中是否存在某个属性 getattr ...

  3. springmvc下载一个文档下载接口里的文档

    A提供了一个文件下载的接口,在调用的时候可以直接在前端用a标签来调用 <a href="http://" target="_blank">下载< ...

  4. Spring 集成 Redis

    pom.xml <dependency> <groupId>org.springframework.data</groupId> <artifactId> ...

  5. java-多线程的练习----妖,等待唤醒,代码重构,lock到condition

    1 需求 资源有姓名和性别. 两个线程,    一个负责给姓名和性别赋值,    一个负责获取姓名和性别的值. 要求1,运行一下,解决程序的 "妖"的问题. 要求2,实现正确数据的 ...

  6. python 数据标准化

  7. javascript最大公约数与最小公倍数

    var a = 5 ; var b = 15 ; var min = Math.min(a,b); var max = Math.max(a,b); // for循环求最大公约数 for(var i ...

  8. MySQL Daemon failed to start错误解决办法是什么呢?

    首先我尝试用命令:service mysql start 来启动服务,但是提示: MySQL Daemon failed to start 一开始出现这个问题我很方,然后开始查,说什么的都有,然后看到 ...

  9. PHP把图片保存到数据库,将图片本身保存在数据库,而非保存路径

    备注 百度开发者的云代码空间为了保证高可用,不允许用户将图片保存到代码空间中,使用CDN或者对象存储不仅收费而且使用比较复杂,于是考虑能否将img存储在数据库中,虽然很多人说会造成性能问题,权当一试 ...

  10. web前端学习(四)JavaScript学习笔记部分(4)-- JavaScriptDOM对象

    1.Javascript-DOM简介 1.1.HTML DOM 1.2.DOM操作HTML 1.2.1.JavaScript能够改变页面中的所有HTML元素 1.2.2.JavaScript能够改变页 ...