2013-04-18 79 views
0

我试图解析具有以下信息解析C++中的文件,而忽略某些字符

test_wall ; Comments!! 
je,5 
forward 
goto,1 
test_random; 
je,9 

我应该忽略后注释文件中的“;”并转到下一行。当有逗号时,我试图忽略逗号并存储第二个值。

string c; 
int a; 

c=getChar(); 

ifstream myfile (filename); 
if (myfile.is_open()) 
{ 
    while (c != ';' && c != EOF) 
    { 
     c = getchar(); 
     if(c == ',') 
     { 
     a= getChar(); 
     } 

    } 
} 
myfile.close(); 
} 
+1

你的'getchar'调用没有引用流 - 它们将等待标准输入(例如键盘)。 – 2013-04-18 05:18:00

+0

我怎样才能忽略逗号呢? – 2013-04-18 05:24:51

+0

看来你需要'std :: string line; while(getline(myfile,line){std :: string :: size_type comma_pos = line.find(','); std :: string :: size_type semicolon_pos = line.find(';'); if(pos!= std :: string :: npos &&(semicolon_pos == std :: string :: npos || semicolon_pos> comma_pos))store(line [comma_pos + 1]);}' – 2013-04-18 05:47:27

回答

1

下面是一些代码。我不完全相信我已经正确地理解了这个问题,但是如果不希望这会让你朝正确的方向发展。

ifstream myfile (filename); 
if (myfile.is_open()) 
{ 
    // read one line at a time until EOF 
    string line; 
    while (getline(myFile, line)) 
    { 
     // does the line have a semi-colon? 
     size_t pos = line.find(';'); 
     if (pos != string::npos) 
     { 
      // remove the semi-colon and everything afterwards 
      line = line.substr(0, pos); 
     } 
     // does the line have a comma? 
     pos = line.find(','); 
     if (pos != string::npos) 
     { 
      // get everything after the comma 
      line = line.substr(pos + 1); 
      // store the string 
      ... 
     } 
    } 
} 

我已经留下部分评论'存储字符串'空白,因为我不确定你想在这里做什么。在存储之前,您可能会要求将字符串转换为整数。如果是这样,然后添加该代码,或询问你是否不知道该怎么做。其实不要问,搜索堆栈溢出,因为那个问题已经被问了几百次了。

+0

谢谢@约翰。这真的很有帮助。 – 2013-04-18 06:34:28