栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++读取(utf-8)txt文件将字符串转换为整形时stoi函数报错

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++读取(utf-8)txt文件将字符串转换为整形时stoi函数报错

这里是在linux系统下运行的,windows应该也一样

创建文件

文本文件1.txt里保存的是110 200的内容,目的是读取这些内容然后利用stoi函数将其转换成整形输出。

110 200
//aaa.cpp
#include
#include
#include
using namespace std;
int main(){
    fstream fs;
    fs.open("./1.txt",ios::in);
    string line;
    getline(fs,line);
    int ind=line.find(' ');
    int u=stoi(line.substr(0,ind));
    int v=stoi(line.substr(ind+1));
    cout<
    //     cout< 
编译 
g++ -std=c++11 -o aaa aaa.cpp

命令生成一个aaa的可执行文件

运行
./aaa

报错信息如下:意思是stoi函数报错,无效的参数

正常情况下是没有问题的,但是这里将110和220转换的时候却出错了,然后我就逐个字符输出了一下,发现了问题。

#include
#include
#include
using namespace std;
int main(){
    fstream fs;
    fs.open("./input-file/1.txt",ios::in);
    string line;
    getline(fs,line);
    int ind=line.find(' ');
    // int u=stoi(line.substr(0,ind));
    // int v=stoi(line.substr(ind+1));
    cout<
        cout< 

输出结果:

这里上边完整输出了字符串,下边却多出了三个乱码字符,所以调用stoi函数时会出错,上网查了下这个是文件头部的bom头,是utf-8 with bom格式下才会有的,所以将格式转换一下就好了,转换车utf-8格式

利用vscode转换格式


打开1.txt文件,在右下角看见格式是utf-8 with bom的,点击选择通过编码保存

之后重新编译,运行,成功输出

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/925490.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号