c++ - 从文本文件中读取和比较行

标签 c++

我有这段代码,我想从文本文件中读取行并从该行中找到唯一的代码。这是我的文本文件中的一些内容:

AGU UAC AUU GCG CGA UGG GCC UCG AGA CCC GGG UUU AAA GUA GGU GA

GUU ACA UUG CGC GAU GGG CCU CGA GAC CCG GGU UUA AAG UAG GUG A

UUA CAU UGC GCG M GGC CUC GAG ACC CGG GUU UAA AGU AGG UGA

UGG M AAA UUU GGG CCC AGA GCU CCG GGU AGC GCG UUA CAU UGA

我想找到包含字母 'M' 的行,并将它们分成单独的字符串,以便我可以进一步分解它们并进行比较。不过我有点麻烦。 我试图找到它们并将其分配给一个字符串,但它似乎将所有行都分配给了同一个字符串。这是我目前所拥有的:

ifstream code_File ("example.txt");   // open text file.
if (code_File.is_open()) {
   while (code_File.good()) {
      getline(code_File,line);    //get the contents of file 
      cout  << line << endl;     // output contents of file on screen.
      found = line.find_first_of('M', 0);               // Finding start code
      if (found != string::npos) {
         code_Assign.assign(line, int(found), 100);        
         /* assign the line to code_Assign and print out string from where I 
            found the start code 'M'. */
         cout << endl << "code_Assign: " << code_Assign << endl << endl;

ED:我应该使用字符串替换而不是赋值吗?

最佳答案

您每次迭代都重写 code_Assigncode_Assign.assign(line, int(found), 100);line 中为字符串分配一个内容,之前的内容丢失.使用替换也不会。您需要将字符串存储在某处,最简单的方法是使用 vector

你像这样声明一个空的字符串 vector :

std::vector<std::string> my_vector_of_strings;

与普通数组不同, vector 会在您向其添加元素时动态调整自身大小,因此您无需在编译时知道它需要多大。更多信息在这里:vector reference .

下一步,

   while (code_File.good()) {
        getline(code_File,line); 

是错误的形式,之前已经在 SO 上解释过很多次(例如 here )。 在 while 条件下移动 getline() 调用。您的代码应如下所示:

// untested

ifstream code_File ("example.txt");   // open text file.
vector<string> vec_str;               // declare an empty vector of strings
string line;

if (code_File.is_open())
    while (getline(code_File, line)) { // read a line and only enter the loop if it succeeds 
        size_t found = line.find_first_of('M');  // you can omit the second parameter, it defaults to 0 
        if (found != string::npos) {
             line = line.substr(found); // take a substring from where we found 'M' to the end 
             vec_str.push_back(line);   // add the line to the vector
        }
    }

// print out the lines in vector:

for (size_t i = 0; i < vec_str.size(); i++)
    cout << vec_str[i] << endl;

// or, prettier, using the new c++11's range based for:

for (string s& : vec_str) cout << s << endl;

希望对您有所帮助。

关于c++ - 从文本文件中读取和比较行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8222563/

相关文章:

c++ - 移位寄存器74HC595输出电流

C++ 字符串小写与自定义语言环境

c++ - 在运行时决定一个应用程序属于控制台/windows 子系统

c++ - QSettings - 读取路径值的方式是什么?

c++ - 任何免费的 Qt 内存泄漏检测器?

c++ - QT setMouseTracking(true) 完全没有效果

c++ - 如何在 SetWindowPos() 之后同步窗口的系统菜单?

c++ - 分配给 std::tie 和引用元组有什么区别?

c++ - 如何为 std::string 可变参数模板参数调用 c_str()?

c++ - 当成员具有另一个类作为其类型时,在构造函数中进行成员初始化