c++读文件的一个简洁的问题

####问题背景:
读文件的时候发现第一个字符是空的;

img

img

img


代码:

//读取ToBeTran.txt
    ifstream ifs;
    ifs.open("ToBeTran.txt", ios_base::in);
    if (!ifs.is_open()) 
        cout << "文件ori.txt打开失败" << endl;
    char s[1000];
    cout << "文件类容:";
    while (ifs>>s) { cout << s; }
    cout << endl;
    ifs.close();

    for (int i = 0; i < 10; ++i)
        cout << "s["<"]="<

###尝试。
吧while后面的{}删掉后可以输出s[0]=a;
但是 判断s[0]==a 时会返回false
在文件里a前面加入空格也没用。

望采纳

你的代码中使用了 ifs>>s 这种方式来读取文件中的内容,这种方式会自动忽略开头的空白符(如空格、回车、制表符等)。如果想要读取文件中所有的字符,包括空白符,可以使用 getline 函数。

string line;
while (getline(ifs, line)) {
    cout << line;
}