簡體   English   中英

使用頭文件和cpp文件在c ++中解析字符串

[英]Parsing a string in c++ using header file and cpp file

我能夠閱讀我的文本文件。 現在,我想逐行解析字符串。 我正在使用頭文件和cpp文件..有人可以幫我解析教程嗎。 在哪里可以找到很好的解析教程?

您可以嘗試http://www.cppreference.com/wiki/並查看使用字符串流的示例。

我看不到它與頭文件有什么關系,但是這是您逐行解析流的方式:

void read_line(std::istream& is)
{
  // read the lisn from is, for example: reading whitespace-delimited words:
  std::string word;
  while(is >> word)
    process_word(word);
  if( !is.eof() ) // some other error?
    throw "Dude, you need better error handling!";
}

void read_file(std::istream& is)
{
  for(;;)
  {
    std::string line;
    if( !std::getline(is,line) )
      break;
    std::istringstream iss(line);
    read_line(iss);
  }
  if( !is.eof() ) // some other error?
    throw "Dude, you need better error handling!";
}

嘗試這個:

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

using namespace std;

int main()
{
    ifstream fs("myFile.txt");
    string input;
    vector<string> sets;
    while( getline(fs, input) )
        sets.push_back(input);
}

首先,您需要知道這些行是包含固定長度的字段還是可變長度的字段 固定長度字段通常填充一些字符,例如空格或零。 可變長度字段通常以逗號或制表符之類的字符終止。

可變長度字段

使用std::string::findstd::string::find_first查找結尾字符; 也要考慮字符串的末尾,因為最后一個字段可能不包含終止字符。 使用此位置確定字段的長度(結束字段位置-起始字段位置)。 最后,使用std::string::substr提取字段的內容。

固定長度字段

使用std::string::substr方法提取文本。 可以使用先前字段(如果有)的累計長度和當前字段的大小來計算開始和結束位置。

轉換字段文字

該字段的內容可能不是字符串,需要轉換為內部數據類型。 例如,一個數字。 使用std::istringstream將字段的文本轉換為內部數據類型。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM