2013-12-14 62 views
0

我有一個文件,格式如下:讀取字符

# This is one comment 
# Another comment 

但問題是運行下面的代碼時:

char c; 
    string string1; 
    while ((c = fgetc(file)) == '#') { 
     string1 += c; 
     while ((c = fgetc(file)) != '\n') { 
      string1 += c; 
     } 
    } 

輸出是:

# This is one comment# Another comment 

我知道在第一次評論中的'\ n'並沒有保存在string1中,但是我怎樣才能用這種方法或類似方法解決呢?

+2

使用['std :: getline'](http://en.cppreference.com/w/cpp/string/basic_string/getline) – pyon

+0

該代碼沒有輸出,也不完全清楚你想要的輸出成爲。 – RichardPlunkett

+0

@EduardoLeón - 'getline'也會吞下換行符。 –

回答

1

試試這個:

char c; 
string string1; 
while ((c = fgetc(file)) == '#') { 
    string1 += c; 
    while ((c = fgetc(file)) != '\n') { 
     string1 += c; 
    } 
    string1 += c; 
} 

因爲程序進入了第二個循環後,ç的價值是 '\ n',你可以把它放在你的字符串1

這是我的測試.cpp文件,你可以試試看:

#include <iostream> 
#include <string> 
#include <cstdio> 

using namespace std; 

int main(){ 
    char c; 
    string string1; 
    FILE * file = fopen("test.in","r"); 

    while ((c = fgetc(file)) == '#') { 
     string1 += c; 
     while ((c = fgetc(file)) != '\n') { 
      string1 += c; 
     } 
     string1 += c; 
    } 
    cout<<string1<<endl; 

    return 0; 
} 

而「test.in」是你想要輸入的文本。

謝謝。