2013-08-31 134 views
-1

我有一个文本文件,其中包含#...它看起来像这样。C++的字符串解析

#Stuff 
1 
2 
3 
#MoreStuff 
a 
b 
c 

我试图使用的std :: string ::找到()函数来获取#的位置,然后从那里走,但我不知道如何真正的代码这一点。

这是我的尝试:

int pos1=0; 
while(i<string.size()){ 
    int next=string.find('#', pos1); 
    i++;} 
+1

究竟是你想读什么? – chris

+0

来自用户的输入,以该格式给出。我使用getline将它们的输入存储在一个字符串中 – Dark

+0

“我用getline将它们的输入存储在一个字符串中” - 那是当你第一次一行一行地解析文件时......为什么不找' '在那里签字? – LihO

回答

0

很难从你的问题告诉你的“位置”的意思,但它看起来像你正在尝试做这样的事情:

#include <fstream> 
#include <iostream> 

int main() 
{ 
    std::ifstream incoming{"string-parsing-for-c.txt"}; 
    std::string const hash{"#"}; 
    std::string line; 
    for (auto line_number = 0U; std::getline(incoming, line); ++line_number) 
    { 
     auto const column = line.find(hash); 
     if (std::string::npos != column) 
     { 
      std::cout << hash << " found on line " << line_number 
         << " in column " << column << ".\n"; 
     } 
    } 
} 

...或者可能是这样的:

#include <fstream> 
#include <iostream> 

int main() 
{ 
    std::ifstream incoming{"string-parsing-for-c.txt"}; 
    char const hash{'#'}; 
    char byte{}; 
    for (auto offset = 0U; incoming.read(&byte, 1); ++offset) 
    { 
     if (hash == byte) 
     { 
      std::cout << hash << " found at offset " << offset << ".\n"; 
     } 
    } 
} 
0

这里有一个我做了一个前一阵子...(C语言)

int char_pos(char c, char *str) { 
    char *pch=strchr(str,c); 
    return (pch-str)+1; 
} 

它移植到C++和你去那里! ;)

  • If:Not Found Then returns Negative。
  • 否则:返回“积极”,字符的第1个发现的位置(第一次比赛)