简体   繁体   English

从文本文件中读取大块行到字符串

[英]Reading chunks of line from text file into strings

So say if I have this line in a text file. 所以说如果我在文本文件中有这一行。

AarI/CACCTGCNNNN'NNNN/'NNNNNNNNGCAGGTG//

What I want is to read this line into a string until the forwardslash appears and then start reading the next set of characters into another string.. So in this example I would have 3 strings containing 我想要的是将这行读入字符串,直到出现正斜杠,然后开始将下一组字符读入另一个字符串。因此,在此示例中,我将包含3个字符串

string1 =  "AarI"
string2 = "CACCTGCNNNN'NNNN"
string3 = "'NNNNNNNNGCAGGTG"

Any idea how to go about this? 任何想法如何去做?

istream::getline() with a delim character of '/' - see: http://www.cplusplus.com/reference/istream/istream/getline/ 带有'/'字符的istream::getline() -请参阅: http : //www.cplusplus.com/reference/istream/istream/getline/

Not the best or safest, probably amongst the simpler approaches. 不是最好或最安全的方法,可能是较简单的方法中的方法。

Use sstream . 使用sstream The code below shows an example of how to split a string. 下面的代码显示了如何分割字符串的示例。

#include <iostream>
#include <vector>
#include <string>
#include <sstream>

using namespace std;

vector<string> split(string str, char delimiter);

int main(int argc, char **argv) {

  string DNAstr = "AarI/CACCTGCNNNN'NNNN/'NNNNNNNNGCAGGTG//";
  vector<string> splittedlines = split(DNAstr, '/');

  for(int i = 0; i < splittedlines.size(); ++i)
    cout <<""<<splittedlines[i] << " \n";

  return 0;
} 


vector<string> split(string str, char delimiter) {
  vector<string> buffer;
  stringstream ss(str); 
  string tok;

  while(getline(ss, tok, delimiter)) {
    buffer.push_back(tok);
  }

  return buffer;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM