2013-12-14 65 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”是你想要输入的文本。

谢谢。