C++从文件按行读取字符串遇到的转义字符问题

 在从文件读取字符串过程中遇到的坑,记录一下。

当字符串中存在转义字符时,用getline()函数从文件按行读取出来时,‘\t’转义字符被转换成了两个字符,如下程序所示。

文件中读出的“hello\tworld\n”的size为14,而字符串中“hello\tworld\n”的size为12,在使用时应注意这个问题。

#include <string>
#include <fstream>
#include <iostream>

int main(int argc, const char * argv[]) {
    std::string filepath  = "file.txt";
    std::ifstream in(filepath,std::ios::in);
    std::string line;
    if (!in.fail()) {
        while (getline(in, line)) {
            std::cout << line << ", size is " << line.size() << std::endl;
        }
        in.close();
    } else {
        return 0;
    }
    std::string s = "hello\tworld\n";
    std::cout<<s<<" size is " << s.size()<<std::endl;
    return 0;
}

结果:

C++从文件按行读取字符串遇到的转义字符问题