这里是在linux系统下运行的,windows应该也一样
创建文件
文本文件1.txt里保存的是110 200的内容,目的是读取这些内容然后利用stoi函数将其转换成整形输出。
110 200
//aaa.cpp
#include<iostream>
#include<fstream>
#include<string>
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<<line<<endl;
cout<<u<<"\t"<<v<<endl;
// for(int i=0;i<line.size();i++){
// cout<<line[i]<<"\t";
// }
// cout<<endl;
}
编译
g++ -std=c++11 -o aaa aaa.cpp
命令生成一个aaa的可执行文件
运行
./aaa
报错信息如下:意思是stoi函数报错,无效的参数
正常情况下是没有问题的,但是这里将110和220转换的时候却出错了,然后我就逐个字符输出了一下,发现了问题。
#include<iostream>
#include<fstream>
#include<string>
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<<line<<endl;
// cout<<u<<"\t"<<v<<endl;
for(int i=0;i<line.size();i++){
cout<<line[i]<<"\t";
}
cout<<endl;
}
输出结果:
这里上边完整输出了字符串,下边却多出了三个乱码字符,所以调用stoi函数时会出错,上网查了下这个是文件头部的bom头,是utf-8 with bom格式下才会有的,所以将格式转换一下就好了,转换车utf-8格式
利用vscode转换格式
打开1.txt文件,在右下角看见格式是utf-8 with bom的,点击选择通过编码保存
之后重新编译,运行,成功输出