C++读取string字符串的N种方式以及常见问题

1.实现


  1. 整行读取(包括空格)
    直接用cin读取string的话如果遇到空格会断开,用下面的语句就可以读取包含空格的字符串:
	getline(cin,sLine);

需要注意要getline函数需要先#include <string>


  1. 整行读取(包括空格)2
    一个一个字符读取,读到回车键结束(但并不会读入回车键),如果需要对每个字符进行处理的话这种方法最合适,在OJ中运行可能会出现问题
	string s = "";
	char ch;
	while ((ch = getchar()) != '\n') s+=ch; //此处可以do stuff

  1. 读取整个文件为一个string
#include <iostream>
#include <fstream>
using namespace std;
string read(string path)
{
    ifstream f;
    string text="";
    f.open(path,ios::in);
    if(!f.is_open())
        return "#Error opening#";
    
    string buf;
    while(getline(f, buf))
    {
        text+=buf;
        text+="\n";
    }
    f.close();
    return text;
}

  1. 逐行读取整个文件为一个string数组(每一行为一个string)
#include <vector>
#include <iostream>
#include <fstream>
using namespace std;
vector<string> readLines(string path)
{
    ifstream f;
    vector<string> lines;
    string buf;
    f.open(path,ios::in);
    if(f.is_open())
        while(getline(f, buf))
            lines.push_back(buf);
    f.close();
    return lines;
}

2.问题

  1. 控制台输出中文乱码:

    Windows(中文)默认的字符集是Windows-936(GBK),mingw的内部是GCC,而GCC编译器默认编译的时候是按照UTF-8解析和输出的,当未指定字符集时一律当作UTF-8进行处理,于是造成乱码。

解决方案:

	system("@chcp 65001");  //会有回显

或:
(需包含头文件windows.h)

SetConsoleOutputCP(65001);

将控制台编码设置为utf8

  • 12
    点赞
  • 53
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中可以使用InputStreamReader和FileInputStream来按指定编码格式读取txt文件。具体实现方法如下: ```java File file = new File("example.txt"); // 文件路径 String charset = "UTF-8"; // 指定编码格式 StringBuilder sb = new StringBuilder(); try (InputStreamReader isr = new InputStreamReader(new FileInputStream(file), charset); BufferedReader br = new BufferedReader(isr)) { String line; while ((line = br.readLine()) != null) { sb.append(line).append(System.lineSeparator()); // 按行读取并添加到StringBuilder中 } } catch (IOException e) { e.printStackTrace(); } String content = sb.toString(); // 读取的文件内容 System.out.println(content); ``` 上述代码中,我们首先创建了一个File对象,指定了要读取的文件路径。然后使用InputStreamReader和FileInputStream来按指定编码格式读取文件,并使用BufferedReader按行读取文件内容,将每行内容添加到StringBuilder中。最后将StringBuilder转换为字符串并输出。 如果要写入指定编码格式的txt文件,可以使用OutputStreamWriter和FileOutputStream。具体实现方法如下: ```java File file = new File("example.txt"); // 文件路径 String charset = "GBK"; // 指定编码格式 try (FileOutputStream fos = new FileOutputStream(file, true); OutputStreamWriter osw = new OutputStreamWriter(fos, charset); BufferedWriter bw = new BufferedWriter(osw)) { bw.write("新加的" + charset + "字符,原来的一行是" + charset + "格式"); bw.newLine(); // 换行 } catch (IOException e) { e.printStackTrace(); } ``` 上述代码中,我们首先创建了一个File对象,指定了要写入的文件路径。然后使用OutputStreamWriter和FileOutputStream来按指定编码格式写入文件,并使用BufferedWriter写入文件内容,最后使用newLine()方法换行。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值