QTextStream读取文本忽略空格
时间: 2023-11-26 22:18:59 浏览: 110
可以使用 QTextStream 的 setCodec() 方法设置 QTextCodec::codecForName("UTF-8") 编码,并使用 QTextStream 的 setFieldWidth(0) 方法忽略空格。具体代码如下:
QFile file("test.txt");
if(!file.open(QIODevice::ReadOnly | QIODevice::Text))
return;
QTextStream in(&file);
in.setCodec(QTextCodec::codecForName("UTF-8"));
in.setFieldWidth(0);
QString line;
while(!in.atEnd())
{
line = in.readLine();
// 处理读取的每一行文本
}
file.close();
相关问题
QTextStream读取文本不要忽略空格
可以使用QTextStream的QTextStream::setFieldWidth()函数来设置读取文本时的字段宽度,然后再使用QTextStream::skipWhiteSpace()函数来跳过前面的空格,具体实现代码如下:
```cpp
QFile file("file.txt");
if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
QTextStream in(&file);
in.setFieldWidth(0); // 不限制字段宽度
while (!in.atEnd()) {
in.skipWhiteSpace(); // 跳过前面的空格
QString line = in.readLine(); // 读取一行文本
// 处理读取到的文本
}
file.close();
}
```
需要注意的是,setFieldWidth()函数默认是限制字段宽度的,所以要将字段宽度设置为0。如果不设置为0,就会忽略空格。
QTextStream读取txt数据
可以使用QFile和QTextStream结合的方式来读取txt数据。首先使用QFile打开txt文件,然后使用QTextStream从文件中读取数据。具体可以参考以下代码:
```
QFile file("data.txt");
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
return;
QTextStream in(&file);
while (!in.atEnd()) {
QString line = in.readLine();
// do something with the line
}
file.close();
```
请注意,上面的代码只是一个示例,您需要根据具体的需求进行修改。
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)