首页 > 解决方案 > 字符串成员不适用于由分隔符分隔的文件中的字符串

问题描述

此代码应该打印字符串的一部分,它是最后一个字符,但是 delimiter(:) 之后的第二部分只打印字符串而不是字符。为什么它不起作用,我该如何解决?

代码:

#include <stdio.h>
#include <iostream>
#include <string>
#include <fstream>

using namespace std;
string info;
void PrintTextFile(){
    ifstream myfile("example.txt");
    if(myfile.is_open()){
        while (getline(myfile, info, ':')){
            cout << info << "   " << info.back() << "\n";    
        }
        myfile.close();
    }
    else {
        cout << "Unable to open file.";
    }
}

int main(int argc, char *argv[]) {    
    PrintTextFile();
    return 0;
}

示例.txt:

Left1:Right1
Left2:Right1
Left3:Right3

我的输出:

Left1        1
Right1
Left2        2
Right2
Left3        3
Right3

预期输出:

Left1        1
Right1       1
Left2        2
Right2       2
Left3        3
Right3       3

标签: c++ifstream

解决方案


这里的问题是,当您为其提供自己的分隔符时,getline它会停止使用换行符作为分隔符。这意味着在您读入的第一个循环中Left1:,丢弃:andinfo留下Left1. 您再次阅读的第二次迭代,直到您看到 an:所以您读入Right1\nLeft2:,丢弃:which leave infowith Right1\nLeft2

您需要做的是读取整行,然后使用字符串流将其解析出来

while (getline(myfile, info)){
    stringstream ss(info)
    while (getline(ss, info, ':') // this works now because eof will also stop getline
        cout << info << "   " << info.back() << "\n";    
}

或者,既然您知道您只需要两个值,请通过阅读该行的每个部分来获取它们,例如

while (getline(myfile, info, ':')){
    cout << info << "   " << info.back() << "\n";  
    getline(myfile, info);
    cout << info << "   " << info.back() << "\n";  
}

推荐阅读